使用 okHttp3 上传动态数量的文件

Upload dynamic number of files with okHttp3

如何使用 OkHttp v3 管理动态文件数量的上传,我已经使用旧版本的 OkHttp 实现了 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.

以下代码是旧版本

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.

但是现在 OkHttp <version>3.0.1</version> 文件上传的代码实现类似于下面的代码(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();

我尝试了与 MultipartBody 相同的逻辑,但没有找到任何有效的解决方案。 或者我是否需要为不同的情况实施相同的 if else。(这是不可行的)

构建器仍然存在,可用于此目的。像之前一样存到本地,循环修改:

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