Amir Amir - 1 year ago 131
Android Question

Send file to server via retrofit2 as object

I want to send an audio file to a server with

. I followed this tutorial but the file is not in the format the server accepts. Based on this tutorial I tried the following:

RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part audio = MultipartBody.Part.createFormData("file", "file", requestBody);

and the interface:

@Headers("Content-Type: application/json")
Call<JResponse> upload(@Part("file") RequestBody file);

But, the
attribute is not sent. (If I change
it exists but then there is another problem)

I want to know how to send a file in following format? Should I convert audio file to

{ 'file' : audio_file }

Answer Source

For finding How to send your file to Server via Retroit following steps may solve your problem:

1- Install PostMan.

2- In PostMan select Post and paste URL then go to Body tab and choose form-data.

3- In Key's part write server file name and In Value's part set type as File and upload desire file.

enter image description here

4- Click in Send and then Generate code.

5- Now you have something like following:

enter image description here

6- Now just one step remain go to your retrofit service and paste info like (In my case I want to upload audio.mp3) :

    Call<JResponse> upload(@Part("file\"; filename=\"audio.mp3\" ") RequestBody file);

And request body would be something like:

File file = new File("YOUR_PATH");
RequestBody temp = RequestBody.create(MediaType.parse("multipart/form-data"), file);

Use this pattern and send it with:

 ServiceHelper.getInstance().sendAudio(temp).enqueue(new Callback<JResponse>() {
            public void onResponse(Call<JResponse> call, Response<JResponse> response) {
                Log.e("test", "onResponse: tst");


            public void onFailure(Call<JResponse> call, Throwable t) {
                Log.e("test", "onResponse: tst");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download