如何使用MultipartEntity从Android发送多个图像到服务器

7
我正在使用以下代码向PHP Web服务发送图像和文本。
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;
}
    }

它完美地工作。但这只是适用于一个图像,我想发送5个图像。

例如:Image1 - Text1 Image2 - Text2 等等。

所以我现在很困惑如何逐个存储5张图片,然后在点击按钮时将这些与其相关联的图像和文本一起发送到服务器。

我正在从手机相机获取图像。

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;
}

上传多个文件到服务器。需要添加以下jar文件:https://dev59.com/FXI-5IYBdhLWcg3wF0Uc。这将有助于您解决问题。 - Harish
6个回答

1
使用这个:
val reqEntity = MultipartEntity()
imagePaths.foreach { path ->
    reqEntity.addPart("path$i", FileBody(file));
}
val client: HttpClient = DefaultHttpClient()
val post = HttpPost(url)
post.setEntity(reqEntity);
val response: HttpResponse = client.execute(post)

0

如需详细信息,请查看我的帖子点击这里

使用MultipartEntity向服务器发送多个图像非常困难。我搜索了很多,但没有找到正确的解决方案,然后我自己想出了一种方法来将多个图像发送到服务器 ,在这里我将所选路径的数组发送到异步任务中,在异步任务中将图像发送到服务器

调用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");

    }
}

//);

为了压缩图像并获取位图,我编写了以下函数*: public Bitmap get_Picture_bitmap(String imagePath) { long size_file = getFileSize(new File(imagePath));
size_file = (size_file) / 1000;// 现在是Kb 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) { // 自动捕获块 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 = "文件". basename($result[0]). "已上传。"; $send_arr['success'] = 1; $send_arr['message'] = $msg; echo json_encode($send_arr); } else { $msg = "抱歉,上传文件时出错。"; $send_arr['success'] = 0; $send_arr['message'] = $msg; echo json_encode($send_arr); }

为什么你不能只是创建一个图像的JSON对象数组并将其转换为base64,然后发送到服务器,在服务器API上读取这些图像并将其转换为字节以用作图像呢? - Pramod mishra

0

尝试在WAMP服务器中增加php.ini文件的post_max_size


0

确保您在服务器上的目录或文件夹是可执行、可写和可读的。我曾经遇到过这个问题,这被称为777权限。相信我,这与其他需要考虑的事情一样重要。


0
为什么您不能只是创建一个json对象的图像数组,将其转换为base64并发布到服务器,在您的服务器api中读取这些图像,将它们转换为字节并用作图像。请检查我的答案并尝试实现。 在Android中如何将数据发布到WCF创建的webservice? 从相机获取的图像存储在sdcard中的uri中,然后读取它们。 您可以按顺序分配图像名称并从uri中读取它们。

因为对于较大的图像,Base64字符串可能非常大,并且有时无法完整发送。因此,将它们作为文件上传是更好的选择。 - Vivek Mishra

-1
请查看以下方法...我在这里使用AQUERY发送多个图像文件。这是执行所有后台网络相关任务(如AJAX)的最佳库。

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();
            }

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接