How to send multipart/form-data with Spring RestTemplate?
Perhaps this example will be useful to find out how you can upload one or more files using Spring.
byte[] fileContent = "testFileContent".getBytes();
String filename = "testFile.xml";
MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
ContentDisposition contentDisposition = ContentDisposition
.builder("form-data")
.name("file")
.filename(filename)
.build();
fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
HttpEntity<byte[]> fileEntity = new HttpEntity<>(fileContent, fileMap);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", fileEntity);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate
.postForEntity("/import/file, requestEntity, String.class);
How to send Multipart form data with restTemplate Spring-mvc
Reading the whole file in a ByteArrayResource
can be a memory consumption issue with large files.
You can proxy a file upload in a spring mvc controller using a InputStreamResource
:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<?> uploadImages(@RequestPart("images") final MultipartFile[] files) throws IOException {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
String response;
HttpStatus httpStatus = HttpStatus.CREATED;
try {
for (MultipartFile file : files) {
if (!file.isEmpty()) {
map.add("images", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));
}
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String url = "http://example.com/upload";
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
response = restTemplate.postForObject(url, requestEntity, String.class);
} catch (HttpStatusCodeException e) {
httpStatus = HttpStatus.valueOf(e.getStatusCode().value());
response = e.getResponseBodyAsString();
} catch (Exception e) {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
response = e.getMessage();
}
return new ResponseEntity<>(response, httpStatus);
}
class MultipartInputStreamFileResource extends InputStreamResource {
private final String filename;
MultipartInputStreamFileResource(InputStream inputStream, String filename) {
super(inputStream);
this.filename = filename;
}
@Override
public String getFilename() {
return this.filename;
}
@Override
public long contentLength() throws IOException {
return -1; // we do not want to generally read the whole stream into memory ...
}
}
Related Topics
How to Set a Timeout on a Spring Boot Rest API
How to Check If an Excel Cell Is Empty Using Apache Poi
How to Click an Li Inside a Ul Using Selenium Webdriver
Replacing Json String With Another String in Java
Looping Within Multiple Arrays in Java Stream
Java.Lang.Noclassdeffounderror: Org/Springframework/Core/Env/Configurableenvironment
Javax.Validation - Allow Null But Validate If the Value Is Not
Creating a Composite Unique Constraints on Multiple Columns
Is There a Simpler Way to Check Multiple Values Against One Value in an If-Statement
How to Make Multiple Line String to Single Line String
The Group Coordinator Is Not Available-Kafka
How to Make Sonar Ignore Some Classes for Codecoverage Metric
Reading Files With Intellij Idea Ide
Spring @Transaction Method Call by the Method Within the Same Class, Does Not Work
How to Read File from Relative Path in Java Project? Java.Io.File Cannot Find the Path Specified