I send the file to the server using Retrofit2 , I use the POST method to send the file, the POST method takes two parameters "file" and "shared-with":

  @Multipart @POST("im-file") Call<RequestBody> sendFile(@Part MultipartBody.Part file, @Part("shared-with") String sharedWith); 

Method to send files to server:

 private void testSendFile(){ File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "gallery.png"); RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestFile); Call<RequestBody> call = BaseApi.getInstance().service.sendFile(body, "bob"); call.enqueue(new Callback<RequestBody>() { @Override public void onResponse(Call<RequestBody> call, Response<RequestBody> response) { Log.e("Response: ", String.valueOf(response)); Log.e("Response headers in send file: ", String.valueOf(response.headers())); Log.e("Response code in send file: ", String.valueOf(response.code())); } @Override public void onFailure(Call<RequestBody> call, Throwable t) { Log.e("File send error: ", t); } }); } 

I get 400 error, "message":"Required request part 'file' is not present","path":"/" .

When testing a request in Postman, everything works:

enter image description here

What could be wrong?

  • And what is the URL in Postman? - Mikhail Vaysman
  • Is file object initialized normally? - post_zeew
  • @post_zeew like, yes - Lucky_girl
  • @MikhailVaysman url in Postman looks like this api.xxxx.net:8000/im-file - Lucky_girl
  • @Lucky_girl confuses me that a different path is mentioned in the error / rather than / im-file - Mikhail Vaysman

1 answer 1

It looks like the name of the part with the file is incorrect. Try

 MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile); 

instead

 MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestFile); 
  • I get the error: @Part parameters using the MultipBody.Part parameters. - Lucky_girl
  • agha corrected the answer. - tse
  • If I change the picture to file, then I get the error Failed to invoke public okhttp3.RequestBody () with no args java.lang.RuntimeException: Failed to invoke public okhttp3.RequestBody () with no args - Lucky_girl
  • one
    This is the next story. In the request description in Call <MyResponse>, the class in which the parser will parse the server response should be specified. normal java class with multiple fields. and you have there ResponseBody. the parser tries to create an instance of this class before filling it, and cannot, because ResponseBody is intended for a completely different one. - tse
  • Thank you very much, earned! - Lucky_girl