Hello. How to transfer a file (jpeg, png, jpg) to a variable via POST in Retrofit 2? There is such a request: request to POSTMAN The request from the screenshot above normally works in Postman. The application has the ability to send along with other data and file. If I do not send the file, then I use the following code:

@FormUrlEncoded @POST("create_user") Call<String> addUser(@Query("token") String token, @FieldMap Map<String, Object> params);

  Map<String, Object> params = new HashMap<>(); params.put("user_id", какое-то_значение); params.put("login", какое-то_значение); params.put("password", какое-то_значение); ApiController.addUser(getToken(getActivity()), params); 

This code is working fine. That is, if the user does not send the file, then everything works. Tell me, please, what you need to finish to be able to send the file. Previously, I reworked the image in base64 and, as a string, inserted it into one of the fields in the request. But now you need to make a request exactly as in the screenshot in Postman.

    2 answers 2

    I saw a link from user pavel163 before. But at night did not notice the switching points. The answer was in the subparagraph Passing Multiple Parts Along a File with @PartMap . The article advised to use FileUtils , but did without it. Below is the code I use.

    Methods from the question have been replaced by the following:

      @Multipart @POST("create_user") Call<String> addUser(@Query("token") String token, @PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part file); File file = new File(mFilePath); MultipartBody.Part body = ApiUtils.prepareFilePart(getActivity(), "image", file); RequestBody login = createPartFromString(mEdtLogin.getText().toString()); RequestBody password = createPartFromString(mEdtPassword.getText().toString()); RequestBody userId = createPartFromString(mUserId + ""); HashMap<String, RequestBody> params = new HashMap<>(); params.put("login", login); params.put("password", password); params.put("user_id", userId); ApiController.addUser(PreferencesUtils.getToken(getActivity()), params, body); 

    The methods createPartFromString () and prepareFilePart () were used. Below is the code:

      private RequestBody createPartFromString(String descriptionString) { return RequestBody.create( okhttp3.MultipartBody.FORM, descriptionString); } @NonNull public static MultipartBody.Part prepareFilePart(Context context, String partName, File file) { String mimeType = URLConnection.guessContentTypeFromName(file.getName()); RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType),file); // MultipartBody.Part is used to send also the actual file name return MultipartBody.Part.createFormData(partName, file.getName(), requestFile); } 
    • in the line `MultipartBody.Part body = ApiUtils.prepareFilePart (getActivity ()," image ", file); What does "image" mean? - zayn1991
    • one
      @ zayn1991 "image" - the name of the variable in which I transfer the image. Above in my question there is a screenshot, it can be seen there. Instead of "image" there will be another name that requires you api, with whom you work. For example, in a real project, I had to update the avatar to the user and, at the request of the api, this variable was called "avatar" (this line was instead of "image"). - Aleator

    Here in this article is a sample code on the android side and on the server side. Sending any file to the server.

     public interface FileUploadService { @Multipart @POST("upload") Call<ResponseBody> upload( @Part("description") RequestBody description, @Part MultipartBody.Part file ); } private void uploadFile(Uri fileUri) { // create upload service client FileUploadService service = ServiceGenerator.createService(FileUploadService.class); // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java // use the FileUtils to get the actual file by uri File file = FileUtils.getFile(this, fileUri); // create RequestBody instance from file RequestBody requestFile = RequestBody.create( MediaType.parse(getContentResolver().getType(fileUri)), file ); // MultipartBody.Part is used to send also the actual file name MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestFile); // add another part within the multipart request String descriptionString = "hello, this is description speaking"; RequestBody description = RequestBody.create( okhttp3.MultipartBody.FORM, descriptionString); // finally, execute the request Call<ResponseBody> call = service.upload(description, body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Log.v("Upload", "success"); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e("Upload error:", t.getMessage()); } }); } 
    • This is not a solution, you do not have the answer to the question. This is an unsubscribe "think you yourself a fishing rod" - no better than sending "go to google, look for it there." Article in English. In general, no matter how you look - your remark draws on the answer. It is necessary to make it and comment, or rewrite the main points from the text by reference. - AK