http://www.androidside.com/plugin/mobile/board.php?bo_table=B49&wr_id=138319
public class ImageUpload extends Activity implements OnClickListener,
OnGestureListener {
private Button image_ok;
private TextView image_student, image_date, image_select;
private EditText etTitle, etContent;
private Uri imageURI;
private String imageName, teacherid, parentid, stTitle, stContent;
private int iYear, iMonth, iDay;
private String sYear, sMonth, sDay;
private ArrayList<String> imageUrls;
String a = null;
String[] b;
private static final int IMAGE = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_upload);
overridePendingTransition(0, 0);
image_student = (TextView) findViewById(R.id.image_student);
image_date = (TextView) findViewById(R.id.image_date);
image_select = (TextView) findViewById(R.id.image_select);
image_ok = (Button) findViewById(R.id.image_ok);
etTitle = (EditText) findViewById(R.id.image_title);
etContent = (EditText) findViewById(R.id.image_contents);
teacherid = "1";
parentid = "2";
iYear = Calendar.getInstance().get(Calendar.YEAR);
iMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
iDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
image_date.setText(iYear + "년 " + iMonth + "월 " + iDay + "일");
gestureScanner = new GestureDetector(this);
initSildeMenu();
image_select.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// startActivity(new Intent(ImageUpload.this,
// ImageUploadMultiSelect.class));
Intent intent = new Intent(ImageUpload.this,
ImageUploadMultiSelect.class);
startActivityForResult(intent, IMAGE);
/*
* // To open up a gallery browser Intent intent = new Intent();
* intent.setType("image/*");
* intent.setAction(Intent.ACTION_GET_CONTENT);
* startActivityForResult( Intent.createChooser(intent,
* "Select Picture"), 1);
*/
}
});
image_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpUploader uploader = new HttpUploader();
// new HttpUploader().execute(params);
// requestCouponTask().execute(district_id);
try {
int i;
for(i =0 ; i < 15 ; i++){
imageName = uploader.execute(b[i]).get(); //image name이 1이라고?
Log.d("naver2", "결과1:" + imageName);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data); //사진 가져오기
if (resultCode != RESULT_OK) {
Toast.makeText(ImageUpload.this, "사진을 가져오지 못했습니다. 다시 선택해 주세요.",
Toast.LENGTH_LONG).show();
}
switch (requestCode) {
case IMAGE: {// 일단 비어있지 않다면
if (data == null) {
Toast.makeText(ImageUpload.this, "사진을 가져오지 못했습니다. 다시 선택해 주세요.",
Toast.LENGTH_LONG).show();
} else {
imageUrls = data.getStringArrayListExtra("images");
imageUrls.add(a);
b = (String[])imageUrls.toArray(new String[0]);
Log.d("naver2", "결과" + b[0]);
Log.d("naver2", "결과" + b[1]);
Log.d("naver2", "결과" + b[2]);
}
break;
}
}
}
/*
* // To handle when an image is selected from the browser public void
* onActivityResult(int requestCode, int resultCode, Intent data) { if
* (resultCode == RESULT_OK) { if (requestCode == 1) { // imageURI is the
* global variable I’m using to hold the // content: imageURI =
* data.getData(); System.out.println("Current image Path is ----->" +
* getRealPathFromURI(imageURI));
* image_select.setText(getRealPathFromURI(imageURI)); } } }
*/
// Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
android.database.Cursor cursor = managedQuery(contentUri, proj, // Which
// columns
// to
// return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public class HttpUploader extends AsyncTask<String, Void, String> {
protected String doInBackground(String... path) {
String outPut = null;
for (String sdPath : path) {
Bitmap bitmapOrg = BitmapFactory.decodeFile(sdPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
// Resize the image
double width = bitmapOrg.getWidth();
double height = bitmapOrg.getHeight();
double ratio = 400 / width;
int newheight = (int) (ratio * height);
System.out.println("———-width" + width);
System.out.println("———-height" + height);
bitmapOrg = Bitmap.createScaledBitmap(bitmapOrg, 400,
newheight, true);
// Here you can define .PNG as well
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 95, bao);
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeToString(ba, 0);
System.out.println("uploading image now ——–" + ba1);
stTitle = etTitle.getText().toString();
stContent = etContent.getText().toString();
sYear = String.valueOf(iYear);
sMonth = String.valueOf(iMonth);
sDay = String.valueOf(iDay);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("teacherid",
teacherid));
nameValuePairs
.add(new BasicNameValuePair("parentid", parentid));
nameValuePairs.add(new BasicNameValuePair("title", stTitle));
nameValuePairs.add(new BasicNameValuePair("image", ba1));
nameValuePairs.add(new BasicNameValuePair("year", sYear));
nameValuePairs.add(new BasicNameValuePair("month", sMonth));
nameValuePairs.add(new BasicNameValuePair("day", sDay));
nameValuePairs
.add(new BasicNameValuePair("content", stContent));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
Constant.URL_IMAGE);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"utf8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// print responce
outPut = EntityUtils.toString(entity);
Log.i("GET RESPONSE—-", outPut);
// is = entity.getContent();
Log.e("log_tag ******", "good connection");
bitmapOrg.recycle();
} catch (Exception e) {
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
}
return outPut;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equalsIgnoreCase("1")) {
Toast.makeText(ImageUpload.this, "이미지 업로드에 성공하였습니다.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ImageUpload.this, "이미지 업로드에 실패하였습니다.",
Toast.LENGTH_SHORT).show();
}
}
}
}
이미지를 php 서버에 업로드하는 소스입니다... 전체소스입니다.
원래는 한장짜리 이미지만 업로드를 하는 소스였는데 여러장을 올릴 수 있도록 바꾸고 있습니다.
이미지의 위치를 여러장 가져오는 데까지는 성공했는데, 이미지 업로드는 어떻게 여러장 해야하나요?
AsyncTask를 여러번 호출하는 수밖에 없나요? 아니면 좋은 방법이 있을까요?
도움을 부탁드립니다 ㅠㅠ
반응형
'차근차근 > Android' 카테고리의 다른 글
Bitmap, BitmapFactory 클래스와 이미지 맵핑 (0) | 2014.08.21 |
---|---|
sd 카드에서 불러올땐 (0) | 2014.08.21 |
GCM 사용하기 2 (단말에 GCM 구현하기) (0) | 2014.07.30 |
안드로이드 GCM(Google Cloud Messaging for Android) 만들기 (0) | 2014.07.30 |
GCM 관련 참고사항입니다 (0) | 2014.07.29 |