Amir Amir - 2 months ago 14
Android Question

Send file to server via retrofit2 as object

I want to send an audio file to a server with

retrofit2
. 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")
@Multipart
@POST("app/")
Call<JResponse> upload(@Part("file") RequestBody file);


But, the
file:
attribute is not sent. (If I change
@Part
with
@Body
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
base64
format?

{ 'file' : audio_file }

Answer

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) :

    @Multipart
    @POST("app/")
    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>() {
            @Override
            public void onResponse(Call<JResponse> call, Response<JResponse> response) {
                Log.e("test", "onResponse: tst");

            }

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

            }
        });