Let's assume I have an endpoint looking like the one below:
@PostMapping(
value = "/something",
consumes = MULTIPART_FORM_DATA_VALUE,
produces = APPLICATION_JSON_VALUE)
public SomeDTO post2Files(
@RequestPart("file1") MultipartFile file1,
@RequestPart("file2") MultipartFile file2 {
In another service I want to read one file from the file system and just resend it, while the file2 is actually a string that I wanna pass as a file through RestTemplate. I tried something like this:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file1", new FileSystemResource(somePath));
body.add("file2", new ByteArrayResource(someString.getBytes()));
restTemplate.postForObject("/something", new HttpEntity<>(body, headers), SomeDTO.class)
It doesn't work and I have no clue why. I get 400. What should I do to make the request pass through?
Figured it out. This is the solution:
body.add("dataSchema", new ByteArrayResource(someString.getBytes()) {
@Override
public String getFilename() {
return "file2";
}
});
It didn't work because the filename did not match with the @RequestPart.