How to manage upload of dynamic number of files with OkHttp v3, I have already implemented with older version of OkHttp which was compile 'com.squareup.okhttp:okhttp:2.6.0'
There are some changes in class Form and Multipart bodies are now modeled. They've replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo. Similarly they've upgraded MultipartBuilder into MultipartBody, MultipartBody.Part, and MultipartBody.Builder.
below code is of older version
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); //Here you can add the fix number of data.
for (int i = 0; i < AppConstants.arrImages.size(); i++) { //loop to add dynamic number of files.
File f = new File(FILE_PATH,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();
//Build the object of MultipartBuilder and get object of RequestBody.
But now for OkHttp
<version>3.0.1</version>
code implementation for file upload is something like below code(source)
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
I tried the same logic with MultipartBody
but didn't found any fruitful solution.
Or do I need to implement same if else
for different cases.(Which is not feasible)
The builder still exists and can be used for this. Store it in a local like you were doing before and modify in the loop:
MultipartBody.Builder buildernew = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", title); //Here you can add the fix number of data.
for (int i = 0; i < AppConstants.arrImages.size(); i++) {
File f = new File(FILE_PATH,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));
}
}
MultipartBody requestBody = buildernew.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With