POST Multipart Form Data using Retrofit 2.0 including image

前端 未结 10 1743
名媛妹妹
名媛妹妹 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:36

    Update Code for image file uploading in Retrofit2.0

    public interface ApiInterface {
    
        @Multipart
        @POST("user/signup")
        Call updateProfilePhotoProcess(@Part("email") RequestBody email,
                                                          @Part("password") RequestBody password,
                                                          @Part("profile_pic\"; filename=\"pp.png")
                                                                  RequestBody file);
    }
    

    Change MediaType.parse("image/*") to MediaType.parse("image/jpeg")

    RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpeg"),
                                             file);
    RequestBody email = RequestBody.create(MediaType.parse("text/plain"),
                                           "upload_test4@gmail.com");
    RequestBody password = RequestBody.create(MediaType.parse("text/plain"),
                                              "123456789");
    
    Call call = apiService.updateProfilePhotoProcess(email,
                                                                        password,
                                                                        reqFile);
    call.enqueue(new Callback() {
    
        @Override
        public void onResponse(Call call,
                               Response response) {
    
            String
                    TAG =
                    response.body()
                            .toString();
    
            UserModelResponse userModelResponse = response.body();
            UserModel userModel = userModelResponse.getUserModel();
    
            Log.d("MainActivity",
                  "user image = " + userModel.getProfilePic());
    
        }
    
        @Override
        public void onFailure(Call call,
                              Throwable t) {
    
            Toast.makeText(MainActivity.this,
                           "" + TAG,
                           Toast.LENGTH_LONG)
                 .show();
    
        }
    });
    

提交回复
热议问题