I had given answer Uploading a large file in multipart using OkHttp but i am stuck with multiple image uploading.
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();
I have ArrayList
of PhotoCaption class which has captionPhoto
and urlPhoto
so how can i addFormDataPart()
I am thinking to make loop and call this function that many times of ArrayList size.
Is there any solution to addFormDataPart() use dynamically?
This answer is for OkHttp2
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();
Dont forget to delete temp. files that you uploaded if it is of no use.