Retrofit(2.0 beta2) Multipart file upload doesn't work

前端 未结 1 1354
温柔的废话
温柔的废话 2020-12-11 06:53

I am using Square Retrofit version 2.0 beta2. I have tried to follow this tutorial .I am trying to upload a bitmap image to the server but somehow code is not working. I hav

1条回答
  •  伪装坚强ぢ
    2020-12-11 07:48

    You are nesting a multipart request body here (A multipart within a multipart).

    Implemented something similar recently, instead of using @Multipart and @Part you can use @Body with MultipartBuilder.

    @POST("/api/photo/user/{userId}")
    Call uploadUserProfilePhoto(@Path("userId") Integer userId, @Body RequestBody photo);
    

    Then instead of using MultipartBuilder.addPart(...) use MultipartBuilder.addFormDataPart(name, filename, requestBody)

    private void uploadProfilePhoto() {
        BeamItService service = BeamItServiceTransport.getService();
    
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg");
        byte [] data = BitmapUtility.getBitmapToBytes(((BitmapDrawable) ivProfilePhoto.getDrawable()).getBitmap());
        Log.d(TAG, String.format("Profile detals => user_id: %d, size of data: %d", 5, data.length));
    
        RequestBody requestBody1 = RequestBody.create(MEDIA_TYPE_PNG, data);
        Log.d(TAG, "requestBody: " + requestBody1.toString());
        RequestBody requestBody2 = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("photo", "t.jpg", requestBody1)
                .build();
        Log.d(TAG, "requestBody: " + requestBody2.toString());
    //  ProfileDetails profileDetails = new DBHelper(this).fetchProfileDetails();
    
        Call call = service.uploadUserProfilePhoto(5, requestBody2);
        call.enqueue(new ProfilePhotoUploadCallback());
    }
    

    0 讨论(0)
提交回复
热议问题