Android - Retrofit 實現圖(多)文上傳提交

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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章