POST Multipart Form Data using Retrofit 2.0 including image

前端 未结 10 1619
名媛妹妹
名媛妹妹 2020-11-22 11:07

I am trying to do a HTTP POST to server using Retrofit 2.0

MediaType MEDIA_TYPE_TEXT = MediaType.parse(\"text/plain\");
MediaType MEDIA_TYPE         


        
10条回答
  •  伪装坚强ぢ
    2020-11-22 11:48

    I am highlighting the solution in both 1.9 and 2.0 since it is useful for some

    In 1.9, I think the better solution is to save the file to disk and use it as Typed file like:

    RetroFit 1.9

    (I don't know about your server-side implementation) have an API interface method similar to this

    @POST("/en/Api/Results/UploadFile")
    void UploadFile(@Part("file") TypedFile file,
                    @Part("folder") String folder,
                    Callback callback);
    

    And use it like

    TypedFile file = new TypedFile("multipart/form-data",
                                           new File(path));
    

    For RetroFit 2 Use the following method

    RetroFit 2.0 ( This was a workaround for an issue in RetroFit 2 which is fixed now, for the correct method refer jimmy0251's answer)

    API Interface:

    public interface ApiInterface {
    
        @Multipart
        @POST("/api/Accounts/editaccount")
        Call editUser(@Header("Authorization") String authorization,
                            @Part("file\"; filename=\"pp.png\" ") RequestBody file,
                            @Part("FirstName") RequestBody fname,
                            @Part("Id") RequestBody id);
    }
    

    Use it like:

    File file = new File(imageUri.getPath());
    
    RequestBody fbody = RequestBody.create(MediaType.parse("image/*"),
                                           file);
    
    RequestBody name = RequestBody.create(MediaType.parse("text/plain"),
                                          firstNameField.getText()
                                                        .toString());
    
    RequestBody id = RequestBody.create(MediaType.parse("text/plain"),
                                        AZUtils.getUserId(this));
    
    Call call = client.editUser(AZUtils.getToken(this),
                                      fbody,
                                      name,
                                      id);
    
    call.enqueue(new Callback() {
    
        @Override
        public void onResponse(retrofit.Response response,
                               Retrofit retrofit) {
    
            AZUtils.printObject(response.body());
        }
    
        @Override
        public void onFailure(Throwable t) {
    
            t.printStackTrace();
        }
    });
    

提交回复
热议问题