使用Retrofit 2上传单个图像似乎没有问题。
然而,我无法弄清如何同时上传两张图片。
如果按照文档操作:http://square.github.io/retrofit/2.x/retrofit/retrofit2/http/PartMap.html
File file = new File(path, "theimage");
File file2 = new File(path2, "theimage");
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("image/png"), file2);
Map<String, RequestBody> params = new HashMap<>();
params.put("image2", requestBody2 );
Call<ResponseBody> call = service.upload(requestBody, params);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
Log.v("Upload", "success");
}
接口:
public interface FileUploadService {
@Multipart
@POST("/upload")
Call<ResponseBody> upload(
//@Part("image_logo\"; filename=\"image.png\" ") RequestBody file,
@Part("file") RequestBody file,
@PartMap Map<String, RequestBody> params
// @Part("description") String description
);
这段代码返回了“上传:成功”,但在服务器端却收到了乱码:
CONTENT_TYPE: multipart/form-data; boundary=50fbfeb3-3abc-4f15-b130-cdcb7e3a0e4f
CONTENT POST:Array ( [file] => �PNG IHDR L 一大堆二进制乱码.... ... 省略 [file2] => �PNG IHDR L 更多二进制乱码...
请问有谁能指导我正确的方向吗?
单文件上传可以正常工作,问题应该不在那里,我现在尝试上传两个或更多图片。
如果我将代码改成这样:
HashMap<String, RequestBody> partMap = new HashMap<String, RequestBody>();
partMap.put("file\"; filename=\"" + file.getName(), requestBody);
partMap.put("file\"; filename=\"" + file2.getName(), requestBody);
Call<ResponseBody> call = service.upload(partMap);
@Multipart
@POST("/upload")
Call<ResponseBody> upload(
@PartMap() Map<String, RequestBody> partMap,
我只能看到第二张图片被上传了,没有乱码... !?
更新
我尝试了这个Retrofit(2.0 beta2) Multipart文件上传不起作用的解决方法,但是收到一个错误提示@body不能与multipart一起使用: Java.lang.IllegalArgumentException: @Body参数不能与表单或多部分编码一起使用。(参数#1)
for (String key : keys) {
Bitmap bm = selectedImages.get(key);
File f = new File(saveToInternalStorage(bm, key), key);
if (f.exists()) {
buildernew.addFormDataPart(key, key + ".png", RequestBody.create(MEDIA_TYPE, f));
}
}
RequestBody requestBody = buildernew.build();
Call<ResponseBody> upload(
@Body RequestBody requestBody