Send file to server via retrofit2 as object

十年热恋 提交于 2019-11-26 11:38:26

问题


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 }

回答1:


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.

4- Click in Send and then Generate code.

5- Now you have something like following:

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");

            }
        });


来源:https://stackoverflow.com/questions/39078192/send-file-to-server-via-retrofit2-as-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!