Retrofit 2 can't upload a file with two additional separate string parameters

ahmadalibaloch picture ahmadalibaloch · Mar 18, 2016 · Viewed 26.1k times · Source

Read edit at bottom of the question for possible alternative solution until the solution is found.

Answer

Shuwn Yuan Tee picture Shuwn Yuan Tee · Apr 11, 2017

I faced similar issue here: Android with Retrofit2 OkHttp3 - Multipart POST Error

I got my problem solved after taking @TommySM suggestion. If is still unclear to you, I think this is the solution:

@Multipart
@POST("jobDocuments/upload")
Call<ResponseBody> upload(
    @Part MultipartBody.Part file,
    @Part("folder") RequestBody folder,
    @Part("name")   RequestBody name);

File file = new File(fileUri.getPath());

// Assume your file is PNG
RequestBody requestFile =
        RequestBody.create(MediaType.parse("image/png"), file);

MultipartBody.Part fileData =
        MultipartBody.Part.createFormData("file", fileName, requestFile);

RequestBody folder = RequestBody.create(
        MediaType.parse("text/plain"),
        "LeadDocuments");

RequestBody name = RequestBody.create(
        MediaType.parse("text/plain"),
        fileName);

// finally, execute the request
Call<ResponseBody> call = service.upload(fileData, folder, name);

The important part is to use MediaType.parse("text/plain") for MediaType of String parameter (I believe your case is: folder & name parameter), using okhttp3.MultipartBody.FORM is a mistake.

See these screenshots for the comparison:

1) Problematic POST

enter image description here

2) Correct POST

enter image description here