通过Retrofit2将文件发送到服务器作为对象 [英] Send file to server via retrofit2 as object

查看:107
本文介绍了通过Retrofit2将文件发送到服务器作为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将音频文件发送到具有retrofit2的服务器.我遵循了教程,但是文件不是以服务器接受的格式.根据本教程,我尝试了以下操作:

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

和界面:

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

但是,不会发送file:属性. (如果我将@Part更改为@Body,则它存在,但是又有另一个问题)

But, the file: attribute is not sent. (If I change @Part with @Body it exists but then there is another problem)

我想知道如何以以下格式发送文件?我应该将音频文件转换为base64格式吗?

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

{ 'file' : audio_file }

推荐答案

以下步骤可以解决如何通过 Retroit 将文件发送到服务器的问题:

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

1-安装 PostMan .

2-在PostMan中选择Post并粘贴URL,然后转到Body选项卡并选择form-data.

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

3-在Key部分中写入服务器文件名,并在Value部分中键入 File 并上传所需文件.

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

4-单击发送,然后生成代码.

5-现在您将看到以下内容:

5- Now you have something like following:

6-现在仅剩一步,请转到您的改造服务并粘贴信息(例如(对于我而言,我想上传audio.mp3):

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

请求正文将类似于:

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

            }
        });

这篇关于通过Retrofit2将文件发送到服务器作为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆