当前位置:  开发笔记 > 编程语言 > 正文

Android okHttp addFormDataPart动态为多个图像

如何解决《AndroidokHttpaddFormDataPart动态为多个图像》经验,为你挑选了2个好方法。

您好AndroidUploaders,

我已经给出了回答使用OkHttp在multipart中上传一个大文件,但我坚持使用多个图像上传.

我想一次动态上传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();

ArrayListPhotoCaption具有类captionPhotourlPhoto那么,如何可以addFormDataPart()

我想循环并调用这个函数多次ArrayList大小.

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



1> Pratik Butan..:

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

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

我希望它会对你有所帮助.



2> Arth Tilva..:

这个答案适用于OkHttp2

对于OkHttp3你可以看到这篇文章.

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

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

别忘了删除 temp.您上传的文件没有用处.


**2016年5月更新**:MultipartBuilder现在由MultipartBody.Builder取代;-)
推荐阅读
linjiabin43
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有