retrofit2.0 上传多张图片
这次写接口后台告诉我说图片按照标准流上传就行了,然后返回是图片地址
{
“data”: [
{
“image2”: “/driver/33461493213676757.png”,
“image1”: “/driver/33461493213676757.png”
}
],
“code”: 200,
“msg”: “请求成功!”
}
在使用PostMan测试过后看到如下结果
那就按照这么写呗
定义接口没啥问题
@Multipart
//不需要加header
// @Headers({"Content-Type: multipart/form-data"})
@POST("V1.0/imgs.action")
Observable<String> upImage(@PartMap Map<String, RequestBody> maps);
一开始我以为要这么写
Map<String, RequestBody> map = new HashMap<>();
for (String path:paths){
File file = new File(path);
//"file\"; filename=\""+file.getName()+"\""
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//注意这里
map.put("name=\"image"+i+"\""+"; filename=\"\"",requestBody);
i++;
}
但是这么写过后直接造成上传的参数读不出来,然后返回就是data中为空
{
“data”: [{}],
“code”: 200,
“msg”: “请求成功!”
}
后来网上差了好多资料,发现在name那边写错了,应这么写
Map<String, RequestBody> map = new HashMap<>();
for (String path:paths){
File file = new File(path);
//"file\"; filename=\""+file.getName()+"\""
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//注意这里
map.put("image"+i+"\""+"; filename=\"\"",requestBody);
i++;
}
注释的含义是该RequestBody 的名称为image+i,上传的文件名称为空
对应了postMan中name=”image1”; filename=”“,至于为什么name=“不加,应该是retrofit2中自动补全了,加上反而就错了。
有时间还是得要好好阅读一下源码