Search code examples
javaspringrestmultipart

MultipartFile failed in RestTemplate with - Bad Request 400 No body


Here is the approach details:

  1. My web application will take the file.
  2. Once upload a file, it received at the server side in the form of MultipartFile.
  3. I will send it to another service as is. (as a MultipartFile).

I am passing the multipart file object to another rest api service. Here is the code.(HTTP method is POST, url is "/uploadDocument")

public ResponseEntity<String> executeMultipartRequest(String url, HttpMethod method, MultipartFile obj){
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", obj.getResource());
        HttpEntity<?> requestEntity = new HttpEntity<>(body, requestHeaders);
        return restTemplate.exchange(url, method, requestEntity, String.class);
    }

This is the service I am calling from above method call:

@PostMapping(value = "/uploadDocument", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("userName") String userName) {
        return null; // removed actual code. 
    }

But when I execute the method I am getting below error:

org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/attest] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [no body]] with root cause org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [no body]

Any idea what exactly the issue is?

I also want to know, is the approach correct?

Any change required?

Any suggestions?

Thanks,

Atul


Solution

  • I am able to send the MultipartFile object via rest api.

    These are the changes I made to existing code which I mentioned in the question.

    This is the working code:

    public ResponseEntity<String> executeMultipartRequest(String url, HttpMethod method, Object obj, Map<String, String> dataMap){
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
            requestHeaders.setCacheControl(CacheControl.noCache());
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            ContentDisposition contentDisposition = ContentDisposition.builder("form-data")
                .name("file")
                .filename(((MultipartFile)obj).getOriginalFilename())
                .build();
            body.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
            body.add("file", ((MultipartFile)obj).getResource());
            body.add("Content-Type", ((MultipartFile)obj).getContentType());
            addData(body, dataMap);
            HttpEntity<?> requestEntity = new HttpEntity<>(body, requestHeaders);
            logger.debug("executeMultipartRequest => before executing rest api request.");
            return restTemplate.exchange(url, method, requestEntity, String.class);
        }
    
    private void addData(MultiValueMap<String, Object> body, Map<String, String> dataMap) {
            if(!dataMap.isEmpty()){
                dataMap.forEach((key, value) -> body.add(key, value));
            }
        }   
    

    The solution I have applied is to send the file as form-data by adding it into the ContentDisposition.

    Set the required properties.

    The end point url is same as mentioned in the question.