내 응용 프로그램에서 사용자가 버튼을 클릭하면 장치 카메라가 시작됩니다. & 사용자가 이미지를 캡처하면 서버에 업로드해야합니다. 이제 이미지를 업로드 할 때 진행률 표시 줄에 업로드 진행률을 표시하려고합니다. 그래서 질문은 이런 식으로, 어떻게하면 xml 파일에 선언 된 진행률 표시 줄에 업로드 진행 상황을 보여줄 수 있도록 서버에 이미지를 업로드 할 수 있습니까? 이제는 작업을 수행하는 방법에 대한 몇 가지 아이디어/예제/샘플 코드가 필요합니다.장치에서 서버로 이미지를 업로드하는 방법 및 진행률 막대를 표시하는 방법 얼마나 많은 데이터가 업로드 되었습니까?
2
A
답변
4
xml 파일에 선언 된 진행률 표시 줄에 업로드 진행 상황을 표시 할 수 있도록 이미지를 서버에 업로드하려면 어떻게해야합니까?
Android - AsyncTask을 사용할 수 있습니다.
다음은 AsyncTask Android: Image upload activity을 사용하여 이미지를 서버에 업로드하는 예입니다.
다음
0
가고 ..
XML 파일 (imageupload.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:id="@+id/ImageView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true" />
<Button android:layout_width="wrap_content" android:id="@+id/Upload"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true" android:text="Upload" />
<EditText android:id="@+id/Caption" android:layout_width="500px"
android:layout_height="wrap_content" android:hint="Write caption"
android:singleLine="true" android:layout_toRightOf="@id/Upload"
android:layout_alignParentBottom="true" />
</RelativeLayout>
ImageUpload.java :
package com.isummation.imageupload;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageUpload extends Activity {
private static final int PICK_IMAGE = 1;
private ImageView imgView;
private Button upload;
private EditText caption;
private Bitmap bitmap;
private ProgressDialog dialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageupload);
imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.Caption);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(ImageUpload.this, "Uploading",
"Please wait...", true);
new ImageUploadTask().execute();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.imageupload_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.ic_menu_gallery:
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}
class ImageUploadTask extends AsyncTask <Void, Void, String>{
@Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
getString(R.string.WebServiceURL)
+ "/cfc/iphonewebservice.cfc?method=uploadPhoto");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("photoId", new StringBody(getIntent()
.getStringExtra("photoId")));
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));
entity.addPart("photoCaption", new StringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
@Override
protected void onProgressUpdate(Void... unsued) {
}
@Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
caption.setText("");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
imgView.setImageBitmap(bitmap);
}
}
imageupload_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/ic_menu_gallery" android:icon="@drawable/ic_menu_gallery"
android:title="Gallery" />
</menu>
관련 문제
- 1. 파일 업로드 진행률 막대 작성 및 Amazon 서버로 이동
- 2. 얼마나 많은 바이트가 지금까지 업로드 되었습니까? 아래
- 3. android에서 파일 업로드 진행률 막대를 구현하는 방법
- 4. 특정 싱크에서 얼마나 많은 데이터가 전송 되었습니까?
- 5. 레일즈 아마존 S3 파일 업로드 진행률 막대를 만드는 방법?
- 6. 모바일 장치에서 서버로 비디오를 업로드하는 "최상의 방법"은 무엇입니까?
- 7. SSL 연결에서 얼마나 많은 데이터가 유출 되었습니까?
- 8. iOS 장치에서 서버로 이미지 업로드
- 9. jsp에서 파일을 업로드하는 동안 진행률 표시 줄을 표시하는 방법
- 10. gridview에 진행률 막대를 추가하는 방법
- 11. imagemagick에서 이미지를 업로드하는 방법
- 12. 장고에서 이미지를 업로드하는 방법
- 13. 코코아 진행률 막대를 사용하는 방법?
- 14. 작업 수행 중 진행률 막대를 업데이트하는 방법
- 15. PHP 업로드 입력 배열 및 얼마나 많은 파일을 찾는 방법?
- 16. 이미지를 HTML5 캔버스에 업로드하는 방법
- 17. 업로드 된 이미지를 파일 시스템에서 표시하는 방법
- 18. 스레드에서 진행률 막대를 업데이트하는 가장 좋은 방법
- 19. 트위터에 이미지를 업로드하는 방법
- 20. 폴더에 이미지를 업로드하는 방법
- 21. 안드로이드에서 이미지를 업로드하는 방법
- 22. 이미지를 업로드하는 가장 간단한 방법
- 23. 이미지를 업로드하는 방법 wp7 serverside.?
- 24. gengt에서 appengine에 이미지를 업로드하는 방법
- 25. 페이스 북 서버에 안드로이드 장치에서 이미지를 업로드하는 방법
- 26. show.php 페이지의 업로드 디렉토리에서 이미지를 표시하는 방법
- 27. asp net에서 페이지로드시 대기 이미지를 표시하는 방법
- 28. 얼마나 많은 데이터가 소켓의 송신 버퍼에 있는지 알려주는 방법
- 29. 얼마나 많은 비트가 사용 되었습니까?
- 30. 얼마나 많은 결과가 반환 되었습니까?