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

11

如何使用OkHttp v3管理上传不定数量的文件,我已经在较早版本的OkHttp中实现了这一功能,其版本为compile 'com.squareup.okhttp:okhttp:2.6.0'

Form和Multipart bodies类有所更改,他们已用更强大的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。(这是不可行的)

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

@jake Wharton,你可以回答这个问题吗?https://stackoverflow.com/questions/52520520/how-to-add-list-of-object-i-e-userdata-type-to-multipartbody-in-okhttpclient - Rahul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接