- 借助 MultipartBody.Part 和 RequestBody 类型参数进行多文件上传:
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (int i = 0; i < files.size(); i++) {
File file = new File(files.get(i).getPath());
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
builder.addFormDataPart("file_name" + i, file.getName(), requestBody);
}
MultipartBody multipartBody = builder.build();
Call call = api.uploadFiles(multipartBody);
- 在 Retrofit 接口声明的方法中使用 @Part List 类型的参数,用于支持多个文件上传:
@Multipart
@POST("upload/files")
Call uploadFiles(@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
List parts = new ArrayList<>();
for (int i = 0; i < files.size(); i++) {
File file = new File(files.get(i).getPath());
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file_name" + i, file.getName(), requestBody);
parts.add(part);
}
Call call = api.uploadFiles(parts);