Send file to server via retrofit2 as object

前端 未结 1 1278
深忆病人
深忆病人 2020-11-30 14:59

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 t

相关标签:
1条回答
  • 2020-11-30 15:27

    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");
    
                }
            });
    
    0 讨论(0)
提交回复
热议问题