使用okHttp3上传动态文件数量

使用okHttp3上传动态文件数量

本文介绍了使用okHttp3上传动态文件数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'

以下代码是旧版本的

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.

但现在用于 OkHttp < version> 3.0.1< / version> 文件上传的代码实现类似于下面的代码( $ b

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

我尝试了与 MultipartBody 没有找到有效的解决办法。
或者我需要为不同的情况实现相同的 if else (这是行不通的)

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

这篇关于使用okHttp3上传动态文件数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!