java Android okHttp addFormDataPart 动态多张图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34395873/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:50:35  来源:igfitidea点击:

Android okHttp addFormDataPart dynamically for Multiple Image

javaandroidimage-uploadingmultipartokhttp

提问by Pratik Butani

Hello AndroidUploaders,

您好 AndroidUploader,

I had given answer Uploading a large file in multipart using OkHttpbut i am stuck with multiple image uploading.

我已经给出了使用 OkHttp 多部分上传大文件的答案但我坚持使用多张图片上传。

I want to upload dynamically 1 to 10image at a time.

我想一次动态上传1 到 10 张图像。

RequestBody requestBody = new MultipartBuilder()
                    .type(MultipartBuilder.FORM)
                    .addFormDataPart(KEY_PHOTO_CAPTION, photoCaption)
                    .addFormDataPart(KEY_FILE, "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                    .build();

I have ArrayListof PhotoCaptionclass which has captionPhotoand urlPhotoso how can i addFormDataPart()

ArrayListPhotoCaption具有类captionPhotourlPhoto这样我怎么能addFormDataPart()

I am thinking to make loop and call this function that many times of ArrayListsize.

我正在考虑进行循环并多次调用ArrayList大小的函数。

Is there any solution to addFormDataPart()use dynamically?

有没有动态使用addFormDataPart() 的解决方案?

回答by Pratik Butani

Here I have created Function to Upload Multiple Images.

在这里,我创建了上传多个图像的功能。

/**
 * Here I am uploading MultipleImages from List of photoCaption
 * Sending photoCaption with URL and Caption of Photo...
 *
 * @param albumId
 * @param photoCaptions
 * @return
 */
public static JSONObject uploadAlbumImage(String albumId, ArrayList<PhotoCaption> photoCaptions) {

    try {

        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        int length = photoCaptions.size();
        int noOfImageToSend = 0;
        for(int i = 0; i < length; i++) {
            /**
             * Getting Photo Caption and URL
             */
            PhotoCaption photoCaptionObj = photoCaptions.get(i);
            String photoUrl = photoCaptionObj.getPhotoUrl();
            String photoCaption = photoCaptionObj.getPhotoCaption();

            File sourceFile = new File(photoUrl);

            if(sourceFile.exists()) {
                /** Changing Media Type whether JPEG or PNG **/
                final MediaType MEDIA_TYPE = MediaType.parse(FileUtils.getExtension(photoUrl).endsWith("png") ? "image/png" : "image/jpeg");

                /** Adding in MultipartBuilder **/
                multipartBuilder.addFormDataPart(KEY_IMAGE_CAPTION + i, photoCaption);
                multipartBuilder.addFormDataPart(KEY_IMAGE_NAME + i, sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile));

                /** Counting No Of Images **/
                noOfImageToSend++;
            }
        }

        RequestBody requestBody = multipartBuilder
                .addFormDataPart(KEY_ALBUM_ID, albumId)
                .addFormDataPart(KEY_IMAGE_COUNT, String.valueOf(noOfImageToSend))
                .build();

        Request request = new Request.Builder()
                .url(URL_ALBUM_UPLOAD_IMAGE)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();

        /** Your Response **/
        String responseStr = response.body().string();

        Log.i(TAG, "responseStr : "+ responseStr);

        return new JSONObject(responseStr);

    } catch (UnknownHostException | UnsupportedEncodingException e) {
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}

I hope it will helps you.

我希望它会帮助你。

回答by Arth Tilva

This answer is for OkHttp2

此答案适用于 OkHttp2

For OkHttp3 You can see this post.

对于 OkHttp3 你可以看到这个帖子

For multiple image you just need to run the loop as per your requirement, remaining part related to request will be same as you do.

对于多个图像,您只需要根据您的要求运行循环,与请求相关的其余部分将与您相同。

  //  final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
final MediaType MEDIA_TYPE=MediaType.parse(AppConstant.arrImages.get(i).getMediaType());

//If you can have multiple file types, set it in ArrayList
                    MultipartBuilder buildernew = new MultipartBuilder().type(MultipartBuilder.FORM)
                            .addFormDataPart("title", title)

                    for (int i = 0; i < AppConstants.arrImages.size(); i++) {
                        File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                TEMP_FILE_NAME + i + ".png");
                        if (f.exists()) {
                            buildernew.addFormDataPart(TEMP_FILE_NAME + i, TEMP_FILE_NAME + i + FILE_EXTENSION, RequestBody.create(MEDIA_TYPE, f));
                        }
                    }
                    RequestBody requestBody = buildernew.build();
                    Request request = new Request.Builder()
                            .url(Url.URL + Url.INSERT_NEWS)
                            .post(requestBody)
                            .build();

                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    return response.body().string();

Dont forget to deletetemp. files that you uploaded if it is of no use.

不要忘记删除temp。如果没有用,您上传的文件