Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload dynamic number of files with okHttp3

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)

like image 246
Arth Tilva Avatar asked Jan 21 '16 17:01

Arth Tilva


1 Answers

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();  
like image 166
Jake Wharton Avatar answered Sep 21 '22 15:09

Jake Wharton