1. 使用 Retrofit 的 partmap實現
比如我們的需求是 修改用戶頭像和用戶姓名;
如果同時需要上傳頭像和用戶名,需要使用 PartMap
進行操作;
@Multipart
@PUT("/myuser/info/update/")
Observable<UserUploadBean> updateUserInfo(@PartMap Map<String, RequestBody> params);
如果僅僅是上傳頭像則可以使用 Part
就可以 :
@Multipart
@PUT("/myuser/info/update/")
Observable<UserUploadBean> updateUserInfo(@Part("photo\";filename=\"file.jpg\"") RequestBody photo);
如果你想使用 Part 同時上傳頭像和修改用戶信息則也是可以的!!
比如:
@Multipart
@PUT("/myuser/info/update/")
Observable<UserUploadBean> updateUserInfo(@Part("photo") RequestBody photo, @Part("name") RequestBody name);
但一定要指定圖片的名稱: filename
;
2. 上傳圖片和文字
注意事項:上傳文字內容需要指定 text/plain ; 圖片 : 要加上 filename
定義 requestbody
// image request body : 多張圖片定義多個
RequestBody requestFile =
RequestBody.create(MediaType.parse("image/png"), file);
RequestBody requestDesc =
RequestBody.create(MediaType.parse("text/plain"), userName);
如果有多張圖片的話,建議使用 PartMap
進行操作
Map<String, RequestBody> bodys = new HashMap<>();
bodys.put("first_name", requestDesc);
bodys.put("photo\";filename=\"" + file.getName(), requestFile);
bodys.put("photo1\";filename=\"" + file.getName(), requestFile1);
上傳方法,和平時使用的 retrofit 一樣;
userServer.updateUserInfo(requestFile, requestDesc);