1

I was using Retrofit 1.9 to upload image like

TypedFile typedFile = new TypedFile("multipart/form-data", new File(ImagePath));

and it's work fine, Now I have to use Retrofit 2 due to response code requirement, so I have changed code accordingly this answer like

RequestBody filebody = RequestBody.create(MediaType.parse("image/*"), file);

I'm passing filebody along with other params to send request, so all other values post properly but imagefile didn't post properly.

For both the case there is no change in API or Server side code, So I'm curious to know Do I have to change server side code or I'm missing something while writing android client code.

have a look on fullcode

RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part filebody = MultipartBody.Part.createFormData("product_img", file.getName(), requestFile);

Call<AddProduct> call = service.sendEditProductRequest(name, filebody );

and the restinterface be like

@Multipart
@POST(EDIT_PRODUCT)
Call<AddProduct> sendEditProfileRequest (            
            @Part("name") RequestBody name,
            @Part MultipartBody.Part filebody);
Hardik Kubavat
  • 251
  • 3
  • 23

2 Answers2

1

Use the following code:

public MultipartBody.Part get(@NonNull File file, @NonNull String key) {
    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    return MultipartBody.Part.createFormData(key, filename, requestFile);
}

More: https://square.github.io/okhttp/3.x/okhttp/okhttp3/MultipartBody.Part.html

0

you can use below code to convert your image file and send with your request.

RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
        MultipartBody.Part.createFormData("image", file.getName(), requestFile);
karan
  • 8,637
  • 3
  • 41
  • 78