Search code examples
javaspringspring-mvcmultipartform-dataresttemplate

MultipartFile is null when sending a file with Rest template


Hi i have 2 separate apps.

the first one is sending post request: i am trying to send a file to the second app

public static String httpPostMultipartFile(String url, File file) throws IOException{
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.add("file", file); // load file into parameter
    HttpHeaders headers1 = new HttpHeaders();
    headers1.setContentType(MediaType.MULTIPART_FORM_DATA);
    String result = restTemplate.exchange(
            url,
            HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, Object>>(parameters, headers1),
            String.class
        ).getBody();
    return result;

this is the second app which is getting post request

@RequestMapping(value = "/fileupload/save", method = RequestMethod.POST, produces = "text/plain")
@ResponseBody
public String save(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam(required = false) Boolean suggestTranspose, @RequestParam(value = "transformers", required = false) String transformersString, @RequestParam(required = false) Integer brandId) throws Exception {
.....
}

But in my second app the MultipartFile is acctually null from the rest call

i have found this link which havnt helped me link 1

link 2


Solution

  • Your httpPostMultipartFile method should be like below. You need to add the file using new FileSystemResource(file.getPath()).

    public static String httpPostMultipartFile(String url, File file) throws IOException{
       RestTemplate restTemplate = new RestTemplate();
            MultiValueMap<String, Object> multipartMap = new LinkedMultiValueMap<String, Object>();     
            multipartMap.add("file", new FileSystemResource(file.getPath()));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<Object> request = new HttpEntity<Object>(multipartMap, headers);         
            String result = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    request,
                    String.class
                ).getBody();
    
            return result;
    }