如何使用 Android 中的 MultipartEntity 将多个图像发送到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12422541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send multiple images to server using MultipartEntity from android
提问by Hardik Joshi
Hello I am sending Images and Text to php webservice using following code.
您好,我正在使用以下代码将图像和文本发送到 php webservice。
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(URL);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
entity.addPart("files[]",
new ByteArrayBody(data, "myImage.jpg"));
entity.addPart("message0", 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(ImageUpload.this, e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
It work perfectly. But this is for only one image send. Now i send 5 images and text with it.
它完美地工作。但这仅用于发送一张图像。现在我用它发送 5 个图像和文本。
Example:- Image1 - Text1
Image2 - Text2 etc..
示例:- Image1 - Text1
Image2 - Text2 等..
So I am confuse about how to store 5 images one by one and at final submit click send images and text associated with it to server.
因此,我对如何一张一张地存储 5 张图像并在最后提交单击时将与其关联的图像和文本发送到服务器感到困惑。
I am get image from Camera only.
我只从相机获取图像。
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
public void onActivityResult_photo(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK) {
if (data != null) {
mImageCaptureUri = data.getData();
display(mImageCaptureUri);
} else {
Toast.makeText(CustomTabActivity.mTabHost.getContext(),
"No photo selected..", Toast.LENGTH_SHORT).show();
}
}
}
private String display(Uri mImageCaptureUri2) {
// TODO Auto-generated method stub
String base64string = null;
try {
if (mImageCaptureUri2 != null) {
System.gc();
selectedImagePath = getPath(mImageCaptureUri2);
File filenew = new File(selectedImagePath);
int file_size = Integer.parseInt(String.valueOf(filenew
.length() / 1024));
if (file_size <= 10000) {
PD1 = ProgressDialog.show(
CustomTabActivity.mTabHost.getContext(), "",
"Loading...");
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
PD1.setCancelable(true);
Bitmap newbitmap;
newbitmap = decodeFile(selectedImagePath);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
newbitmap.compress(Bitmap.CompressFormat.PNG, 50,
bs);
img.setVisibility(View.VISIBLE);
img.setImageBitmap(newbitmap);
byte[] abc = bitmapToByteArray(newbitmap);
if (txt_phototext.getText().toString().equals("")) {
submit.put(abc, "");
} else {
submit.put(abc, txt_phototext.getText()
.toString());
// executeMultipartPost();
}
PD1.dismiss();
}
});
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
CustomTabActivity.mTabHost.getContext());
alertbox.setMessage("Take Image Size Less than 10 MB");
alertbox.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
finish();
}
});
alertbox.show();
}
} else {
System.out.println("===============NULL========");
}
} catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
}
return base64string;
}
static Bitmap decodeFile(String str) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(str), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(str), null,
o2);
} catch (FileNotFoundException e) {
}
return null;
}
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
return bitmapdata;
}
So Finally i am stuck about this please help.
所以最后我被困在这个问题上,请帮忙。
回答by Nabin
And make sure that your directory or folder in server is Executable, Writable and Readable. I had this as the major problem. This is called 777 permission.. Believe me, this is as important as other things to consider.
并确保您在服务器中的目录或文件夹是可执行、可写和可读的。我认为这是主要问题。这称为 777 许可。相信我,这与要考虑的其他事项一样重要。
回答by A.M.N.Bandara
Try increasing the post_max_size of yout php.ini file in WAMP server
尝试增加 WAMP 服务器中 php.ini 文件的 post_max_size
回答by Prashant Maheshwari Andro
For full detail please have a look on my postClick here
有关完整详细信息,请查看我的帖子单击此处
its quite difficult to send multiple images to server using MultipartEntity. I did search for this but didn't find any right solution then i made my own way to send multiple images to server, here i send array of selected paths to asynctask and in asynctask i sent images to server
使用 MultipartEntity 将多个图像发送到服务器非常困难。我确实搜索了这个但没有找到任何正确的解决方案然后我用自己的方式将多个图像发送到服务器,在这里我将选定路径的数组发送到 asynctask 并在 asynctask 中我将图像发送到服务器
Calling Asysnctask Function-new Upload_Multiple.excute(Array_of_Path[]))
调用Asysnctask函数-new Upload_Multiple.excute(Array_of_Path[]))
Private class Upload_Multiple_img extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
protected String doInBackground(String... paths_array) {
String data = "";
for (int i = 0; i < paths_array.length; i++) {
// get_Picture_bitmap() returns bitmap by passing path of image
// get_Picture_bitmap() is mentioned below.
Bitmap bitmap = get_Picture_bitmap(paths_array[i]);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert
DefaultHttpClient httpclient = new DefaultHttpClient();
String server_funtion_url="...serveraddres"+funtion_at_server"";
HttpPost httppost = new HttpPost(server_funtion_url); // server
MultipartEntity reqEntity = new MultipartEntity();
obj_SP = ImagePicker.this.getSharedPreferences("Eperty", 0);
String id_prop = obj_SP.getString("new_prop_id", "");
String Image_Name =
+ String.valueOf(System.currentTimeMillis()) + ".jpg";
// image is a key which is used at server end to get this
reqEntity.addPart("image", Image_Name, in);
httppost.setEntity(reqEntity);
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
data = EntityUtils.toString(response.getEntity());
System.out.println("FFFF== " + data);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return data;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
ConstantData.ToastAlert(ImagePicker.this,
"Images Uploaded successfully");
}
}
//);
//);
For compressing the images and getting bitmap for i made below funtion*
public Bitmap get_Picture_bitmap(String imagePath) { long size_file = getFileSize(new File(imagePath)); size_file = (size_file) / 1000;// in Kb now int ample_size = 1; if (size_file <= 250) { System.out.println("SSSSS1111= " + size_file); ample_size = 2; } else if (size_file > 251 && size_file < 1500) { System.out.println("SSSSS2222= " + size_file); ample_size = 4; } else if (size_file >= 1500 && size_file < 3000) { System.out.println("SSSSS3333= " + size_file); ample_size = 8; } else if (size_file >= 3000 && size_file <= 4500) { System.out.println("SSSSS4444= " + size_file); ample_size = 12; } else if (size_file >= 4500) { System.out.println("SSSSS4444= " + size_file); ample_size = 16; } Bitmap bitmap = null; BitmapFactory.Options bitoption = new BitmapFactory.Options(); bitoption.inSampleSize = ample_size; Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption); ExifInterface exif = null; try { exif = new ExifInterface(imagePath); } catch (IOException e) { // Auto-generated catch block e.printStackTrace(); } int orientation = exif .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); Matrix matrix = new Matrix(); if ((orientation == 3)) { matrix.postRotate(180); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } else if (orientation == 6) { matrix.postRotate(90); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } else if (orientation == 8) { matrix.postRotate(270); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } else { matrix.postRotate(0); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } return bitmap;
} **
Server end Code *
$target_dir = "../webadmin/user_image/"; $target_dir = $target_dir . basename($_FILES["user_img"]["name"]); if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir)) { $msg = "The file ". basename($result[0]). " has been uploaded."; $send_arr['success'] = 1; $send_arr['message'] = $msg; echo json_encode($send_arr); } else { $msg = "Sorry, there was an error uploading your file."; $send_arr['success'] = 0; $send_arr['message'] = $msg; echo json_encode($send_arr); }
用于压缩图像和获取位图,我在下面的功能*
public Bitmap get_Picture_bitmap(String imagePath) { long size_file = getFileSize(new File(imagePath)); size_file = (size_file) / 1000;// in Kb now int ample_size = 1; if (size_file <= 250) { System.out.println("SSSSS1111= " + size_file); ample_size = 2; } else if (size_file > 251 && size_file < 1500) { System.out.println("SSSSS2222= " + size_file); ample_size = 4; } else if (size_file >= 1500 && size_file < 3000) { System.out.println("SSSSS3333= " + size_file); ample_size = 8; } else if (size_file >= 3000 && size_file <= 4500) { System.out.println("SSSSS4444= " + size_file); ample_size = 12; } else if (size_file >= 4500) { System.out.println("SSSSS4444= " + size_file); ample_size = 16; } Bitmap bitmap = null; BitmapFactory.Options bitoption = new BitmapFactory.Options(); bitoption.inSampleSize = ample_size; Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption); ExifInterface exif = null; try { exif = new ExifInterface(imagePath); } catch (IOException e) { // Auto-generated catch block e.printStackTrace(); } int orientation = exif .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); Matrix matrix = new Matrix(); if ((orientation == 3)) { matrix.postRotate(180); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } else if (orientation == 6) { matrix.postRotate(90); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } else if (orientation == 8) { matrix.postRotate(270); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } else { matrix.postRotate(0); bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true); } return bitmap;
} **
服务器端代码 *
$target_dir = "../webadmin/user_image/"; $target_dir = $target_dir . basename($_FILES["user_img"]["name"]); if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir)) { $msg = "The file ". basename($result[0]). " has been uploaded."; $send_arr['success'] = 1; $send_arr['message'] = $msg; echo json_encode($send_arr); } else { $msg = "Sorry, there was an error uploading your file."; $send_arr['success'] = 0; $send_arr['message'] = $msg; echo json_encode($send_arr); }
回答by Pramod mishra
Why you can't just create array of json object of your images to base64 and post to server and at your server api read those images convert to byte and use as image. Check my answe and try to implement. In Android how to post data to webservice which is created in WCF?
为什么您不能只将图像的 json 对象数组创建到 base64 并发布到服务器,然后在您的服务器 api 读取这些图像转换为字节并用作图像。检查我的答案并尝试实施。 在Android中如何将数据发布到在WCF中创建的webservice?
And the images you are getting from camera store them in uri in sdcard and letter read them. You can assign image name sequntialy. And read them from uri.
您从相机获得的图像将它们存储在 uri 中的 sdcard 中,并用字母读取它们。您可以按顺序分配图像名称。并从uri读取它们。
回答by Sajesh Kumar
Please find the below method...here i m sending mutiple image file using AQUERY. The best lib to perform all background network related task.(Like AJAX).
请找到以下方法...这里我使用 AQUERY 发送多个图像文件。执行所有后台网络相关任务的最佳库。(如 AJAX)。
https://code.google.com/p/android-query/
https://code.google.com/p/android-query/
public void uploadImageFile( String filePath,
String message) {
Context context = ApplicationContextProvider.getContext();
String url = SERVER_URL + "/user/uploadImageFile";
try {
Toast.makeText(context, "Uploading...", Toast.LENGTH_SHORT)
.show();
String compressedFile = CommonUtilities.compressImage(filePath,
context);
Map<String, Object> params = new HashMap<String, Object>();
File imageFile = new File(compressedFile);
byte[] imageBytes1 = FileUtils.readFileToByteArray(imageFile);
params.put("imageBytes", imageBytes1);
params.put("message",URLEncoder.encode(message, "UTF-8"));
AQuery aq = new AQuery(context);
aq.ajax(url, params, JSONObject.class,
new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json,
AjaxStatus status) {
Toast.makeText(
ApplicationContextProvider.getContext(),
"Uploaded successfully",
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}