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.