0

I am trying to send Image and Id using retrofit for that i am sending Multipart file and String.

This is my Upload Method on Android side ->

private void UploadFiles() {
        File uploadFile = fileArrayList.get(0);
        if (uploadFile != null) {
            Log.d(TAG, "UploadFiles: File Name is -> " + uploadFile.getName());


            // Parsing any Media type file
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);

            // MultipartBody.Part is used to send also the actual file name
            MultipartBody.Part cropImage = MultipartBody.Part.createFormData("cropImage", uploadFile.getName(), requestFile);

            RequestBody cropId = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile.getParentFile().getName());

            Api.uploadCropImage(cropImage,cropId, new Callback<BasicResponse>() {
                @Override
                public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
                    if (response.body() != null) {
                        Log.d(TAG, "onResponse: Success" + response.body().getResponse());
                    }
                    else{
                        Log.d(TAG, "onResponse: null Response");
                    }
                }

                @Override
                public void onFailure(Call<BasicResponse> call, Throwable t) {
                    Log.d(TAG, "onResponse: Failure");
                }
            });
        }
    }

My Upload CropImage Method ->

public static void uploadCropImage(MultipartBody.Part multipartBody,RequestBody cropId,
                                                                            Callback<BasicResponse> callback) {
        UploadCropImageApi uploadCropImageApi = retrofit.create(UploadCropImageApi.class);
        Call<BasicResponse> call = uploadCropImageApi.uploadCropImage(multipartBody,cropId);
        call.enqueue(callback);
    }

My Interface ->

 public interface UploadCropImageApi {
        @Multipart
        @POST(UPLOAD_FILE_TO_AWS_URL)
        Call<BasicResponse> uploadCropImage(@Part MultipartBody.Part cropImage, @Part("cropId") RequestBody cropId);
    }

This is my Spring Controller, What's wrong with it? It's not printing cropId.

@RequestMapping(value = "/UploadCropImage", method = RequestMethod.POST, consumes = {"multipart/form-data"})
@ResponseBody
public String UploadImage(@RequestBody MultipartFile cropImage,@RequestBody String cropId ,HttpServletRequest request) {
    System.out.println("String is -> " + cropId);
    return null;
}
Avi Patel
  • 475
  • 6
  • 23
  • you mean your output is just "String is -> " ? or doesn't it print anything? – Stultuske Nov 20 '18 at 10:30
  • @Stulttuske,Does not print anything. It just prints some numbers. – Avi Patel Nov 20 '18 at 10:30
  • check whether or not that code is called at all. maybe you are looking in the wrong console. System.out.println will print on the console of the system it runs on. do you run this code on a server? – Stultuske Nov 20 '18 at 10:31
  • It calls only when there is one argument, which is Multipart file. but when i add String parameter it just doesn't print anything. The Response that's been printed on Console is like this 108 1 1 1 0 – Avi Patel Nov 20 '18 at 10:33
  • @Stultuske, i have checked it with Postman and it works when there is only multipart file parameter. Am i doing something wrong passing String Ardument? – Avi Patel Nov 20 '18 at 10:35
  • a Request can (afaik) have only one body – Stultuske Nov 20 '18 at 10:35
  • debug it..i suspect control is not going to syste,.out.print line if you add String parameter. – Alien Nov 20 '18 at 10:35
  • @Stultuske, yes but i am using multipart Request. How can i send multiple parts and get all the parameters using one requestBody? – Avi Patel Nov 20 '18 at 10:36
  • I think you need to use RequestParam instead of body https://stackoverflow.com/questions/28039709/what-is-difference-between-requestbody-and-requestparam calling your Body MultiPartFile doesn't magically make it possible that your body exists out of several types. you can add your String as member of that MultiPartFile class – Stultuske Nov 20 '18 at 10:36

1 Answers1

2

You cannot use two @RequestBody as it can bind to a single object only (the body can be consumed only once)

You need to use @RequestParam String cropId instead of RequestBody.

See here for clarification

UPDATE :Here is your controller method look like

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) 
public @ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) { 
    if (!file.isEmpty()) { 
        try { 
            byte[] bytes = file.getBytes();     
            // Creating the directory to store file 
            String rootPath = System.getProperty("catalina.home"); 
            File dir = new File(rootPath + File.separator + "tmpFiles"); 
            if (!dir.exists()) 
                dir.mkdirs();     
            // Create the file on server 
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name); 
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); 
            stream.write(bytes);
            stream.close(); 
            System.out.println("Server File Location=" + serverFile.getAbsolutePath());
            return null; 
        } catch (Exception e) { 
            return null; 
        } 
    } 
}
Alien
  • 15,141
  • 6
  • 37
  • 57
  • How can i use a POJO class with Multiple File Request and String? i can pass that into RequestBody? – Avi Patel Nov 20 '18 at 10:38
  • 1
    what you can do is let the image come in body and the parameter in request parameter. – Alien Nov 20 '18 at 10:40
  • i want SSL encryption and Body provides encryption while params doesnot. which is provided by spring. – Avi Patel Nov 20 '18 at 10:41
  • can i send Image inside parameter and Id inside Body? – Avi Patel Nov 20 '18 at 11:31
  • is there any way that i can send file via POJO? i have tried it but it does not work. I have tried something like this -> public class CropImageRequest { private String cropId; private MultipartBody.Part cropImage; public String getCropId() { return cropId; } public void setCropId(String cropId) { this.cropId = cropId; } public MultipartBody.Part getCropImage() { return cropImage; } public void setCropImage(MultipartBody.Part cropImage) { this.cropImage = cropImage; } } – Avi Patel Nov 20 '18 at 11:47
  • i have setup the File and String and tried to send it via RequestBody and Multipart Image, it gives the same thing like numbers and does not print the value. – Avi Patel Nov 20 '18 at 11:50
  • i am not able to paste the method in comment so will update the answer..just check once...refer that and send data and file together. – Alien Nov 20 '18 at 11:52
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183949/discussion-between-avi-patel-and-alien). – Avi Patel Nov 20 '18 at 11:54