11

如何使用OkHttp v3 管理动态文件数量的上传,我已经使用旧版本的 OkHttp 实现了compile 'com.squareup.okhttp:okhttp:2.6.0'

现在对 Form 类和 Multipart 主体进行了一些更改。他们用更强大的 FormBody 和 FormBody.Builder 组合替换了不透明的 FormEncodingBuilder。同样,他们将 MultipartBuilder 升级为 MultipartBody、MultipartBody.Part 和 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>文件上传的代码实现类似于下面的代码(源代码

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针对不同的情况实施相同的操作。(这是不可行的)

4

1 回答 1

18

构建器仍然存在并且可以用于此。像以前一样将其存储在本地并在循环中修改:

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();  
于 2016-01-21T17:46:07.580 回答