Reputation: 309
I want to make a multipart request to some external API (created using Spring Boot) but all I get is Required request part 'file' is not present
.
I know the source code of the external API but I can't modify it. It looks like this:
@PostMapping("/upload")
public ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file){
return ResponseEntity.ok().build();
}
And from my application I create and send requests exactly like on the following snippet:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("file", "dupa".getBytes());
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate
.postForEntity("http://api:8080/upload", requestEntity, String.class);
return response.getBody();
What's the reason it doesn't work? The above code rewritten using Apache HttpClient works like charm.
Upvotes: 1
Views: 1069
Reputation: 591
You basically have two options, the solution with byte array:
map.add("file", new ByteArrayResource(byteArrayContent) {
@Override
public String getFilename() {
return "yourFilename";
}
});
I remember having a problem with just adding a byte array, so you need to have a filename too and use ByteArrayResource.
Or adding a File:
map.add("file", new FileSystemResource(file));
Upvotes: 2