用改造2上传单张图片似乎没有问题。
但是,我不知道如何同时上传 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:多部分/表单数据;边界=50fbfeb3-3abc-4f15-b130-cdcb7e3a0e4f
内容发布:数组([file] => �PNG IHDR L alotofbinarygibberish.... ... snip [file2] => �PNG IHDR L 更多二进制乱码...
谁能指出我正确的方向?
单次上传确实有效,所以这不是问题,我正在尝试上传 2 张或更多图片。
如果我将其更改为:
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 file upload doesn't work solution,但得到一个错误,@body can not me used with multipart: Java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding。(参数#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