Search code examples
javaspringspring-bootresttemplate

RestTemplate send file as bytes from one controller to another


assume we have a one controller on third party service which accepts multipart files and its code is like (assume it's running on localhost:9090)

@RequestMapping("/file")
@RestController
public class FileController {

    @RequestMapping(value = "/load", method = RequestMethod.POST)
    public String getFile(@RequestPart("file") MultipartFile file){
        return file.getName();
    }

}

The question is: How write a correct code in my controller, with RestTemplate, that calls the third party service, with file in body?

A few examples that do not work:

First one:

@RequestMapping("/file")
@RestController
public class FileSendController {

    private RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public ResponseEntity<?> sendFile(@RequestPart MultipartFile file) 
    throws IOException {
    String url = "http://localhost:9090/file/load";
    return restTemplate.postForEntity(url, file.getBytes(), 
    ResponseEntity.class);
    }
}

Second one:

@RequestMapping("/file")
@RestController
public class FileSendController {

    private RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public ResponseEntity<?> sendFile(@RequestPart MultipartFile file) 
    throws IOException {
        String url = "http://localhost:9090/file/load";
        byte[] bytes = file.getBytes();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<byte[]> entity = new HttpEntity<>(bytes, headers);
        return restTemplate.exchange(url, HttpMethod.POST, 
        entity,ResponseEntity.class);
    }
}

One restriction: i should load files from memory, so it forces me to use byte[]

All of this examples throw 500 on third party service with message: org.springframework.web.multipart.MultipartException: Current request is not a multipart request.

Thanks for your advices.


Solution

  • Try this:

    MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
    ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getName();
            }
    };
    data.add("file", resource);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(data, requestHeaders);
    
    final ResponseEntity<Response<ImportDto>> responseEntity = restTemplate.exchange(url, 
                        HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<ResponseDto>>(){});