A correct file upload would like this:
HTTP header:
Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ
Http body:
--ABCDEFGHIJKLMNOPQ
Content-Disposition: form-data; name="file"; filename="my.txt"
Content-Type: application/octet-stream
Content-Length: ...
<...file data in base 64...>
--ABCDEFGHIJKLMNOPQ--
and code is like this:
public void uploadFile(File file) {
try {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/file/user/upload";
HttpMethod requestMethod = HttpMethod.POST;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
ContentDisposition contentDisposition = ContentDisposition
.builder("form-data")
.name("file")
.filename(file.getName())
.build();
fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
HttpEntity<byte[]> fileEntity = new HttpEntity<>(Files.readAllBytes(file.toPath()), fileMap);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", fileEntity);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.exchange(url, requestMethod, requestEntity, String.class);
System.out.println("file upload status code: " + response.getStatusCode());
} catch (IOException e) {
e.printStackTrace();
}
}