如何使用 Retrofit 2 post 包含未知数量图像的多部分表单数据?

How to post multipart form data that includes unknown number of images with Retrofit 2?

我正在为 Android 创建一个应用程序,我刚刚开始使用 Retrofit 2。我必须将 ID、名称、代码和照片上传到服务器,但我不知道如何使用 Retrofit 做到这一点2. 从下面class你会看到我不知道我需要上传多少张照片...

我有这个 class:

class Asset {
    private int mId;
    private int mName;
    private int mCode;
    private ArrayList<String> mPhotos;

    // ... constructor
    // ... getters and setters
}

我这是存储库:

class AssetsRepository {
    // ... private fields
    // ... constructor

    public void store(Asset asset, final AssetUploadCompletedCallback callback) {
        // What should be the arguments?
        this.mNPApiService.storeAsset(asset.getCode() /*, ...*/)
               .enqueue(new Callback<String>() {
                   @Override
                   public void onResponse(Call<String> call, Response<String> response) {
                       callback.onAssetUploadCompletedCallback();
                   }

                   @Override
                   public void onFailure(Call<String> call, Throwable t) {
                       //error handling
                   }
               });
    }

}

和 NPApiservice 接口:

interface NPApiService {
    // ... other methods

    @Multipart
    @Post("/assets/{code}")
    Call<String> storeAsset(@Path("code") String code /*, what should go here?*/)
}

我还需要带有百分比的进度条,那么如何附加监听器来告诉我请求的总上传百分比?

这是我的做法。这将上传整个文件夹,您可以相应地更改以处理您的文件。您需要使用多部分格式。

这是一个代码示例:

    @Multipart
    @POST("sync/contact/image")
    Call<Response> ImageUpload(@Part MultipartBody.Part file);

    @Multipart
    @POST("sync/image")
    Call<ResponseBody> MultiImageUpload(@PartMap() Map<String, RequestBody> mapFileAndName);


 public static HashMap<String, RequestBody> GetAllImage(Context context) {
        File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/.ELMEX");
        File[] filesArray = files.listFiles();
        List<File> listOfNames = Arrays.asList(filesArray);
        HashMap<String, RequestBody> map = new HashMap<>(listOfNames.size());
        RequestBody file = null;

        for (int i = 0, size = listOfNames.size(); i < size; i++) {
            file = RequestBody.create(MediaType.parse("multipart/form-data"), listOfNames.get(i));
            map.put("file\"; filename=\"" + listOfNames.get(i).getName() + ".jpg", file);
            file = null;
        }

        return  map;
    }


 HashMap<String, RequestBody> map = UtilImage.GetAllImage(context);

        Call<ResponseBody> call = Retro.getRetroWS().MultiImageUpload(map);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: ");
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });

希望这对您上传多张图片有帮助:

@Multipart @POST(TMB_API_DIR + "/uploadFile") Call<DataResponse> uploadImageFiles(@Part MultipartBody.Part[] partMap, @Query("access_token") String accessToken);

这里我们使用 Array for Part of MultipartBody 和另一个参数,比如 access token。