Android okHttp addFormDataPart动态为多个图像 [英] Android okHttp addFormDataPart dynamically for Multiple Image

查看:3117
本文介绍了Android okHttp addFormDataPart动态为多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello AndroidUploaders,

Hello AndroidUploaders,

我已回答 正在上传使用OkHttp 的多部分大文件,但我遇到了多张图片上传。

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

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

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

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

PhotoCaption我有 ArrayList captionPhoto urlPhoto 那么我怎么能 addFormDataPart()

我想做循环并多次调用这个函数 ArrayList size。

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

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

Is there any solution to addFormDataPart() use dynamically?

推荐答案

这个答案适用于OkHttp2

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

For OkHttp3 You can see this post.

对于多个图像你只需按照你的要求运行循环,与请求相关的剩余部分将与你一样。

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

别忘了删除 temp。您上传的文件,如果它没用。

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

这篇关于Android okHttp addFormDataPart动态为多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆