MultipartFile with SpringBoot
This article explains two use cases of multipart files in Spring Boot.
How to receive a Multipart file in the SpringBoot application?
Suppose we have an endpoint /uploadFile
that receives a file and other parameters as form data in the request body and saves it.
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> uploadFile(@RequestPart(value = "file") MultipartFile file) {
service.uploadFile(file);
return new ResponseEntity<>("success", HttpStatus.OK);
}
PostMapping
annotation is used to represent thatuploadFile
handles HTTP POST requests for the given URI.consumes = MediaType.MULTIPART_FORM_DATA_VALUE
shows that this request accepts multipart media as input data.RequestPart
annotation is used to associate a part of a request namedfile
with a method argumentfile
.service.uploadFile
is a service class method that does further processing, and it is explained below.
Now, we will write a service class method that processes the request input and saves the file.
public void uploadFile(MultipartFile file) throws UserException {
try {
if(file.isEmpty()) {
throw new UserException("Empty file");
}
Path destination = Paths.get("rootDir").resolve(file.getOriginalFilename()).normalize().toAbsolutePath();
Files.copy(file.getInputStream(), destiation);
} catch(IOException e) {
throw new UserException("Store exception");
}
}
file.isEmpty()
is a check to validate the input data.- Next, we create a file with the same input name in the directory named
rootDir
. - The final step is to copy the content of the input file to a newly created file.
How to send a Multipart file using RestTemplate in SpringBoot?
The second use-case of multipart files is to send a file from a spring-boot server to a different server.
Here we are using RestTemplate to communicate with the second server.
public void shareFile(MultipartFile file) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file_name", "testFile");
body.add("file", file.getResource());
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, httpHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity("<url-of-the-second-server>", request, String.class);
}
headers.setContentType(MediaType.MULTIPART_FORM_DATA
is used to specify the content type header for the request.MultiValueMap
represents our request body which containsfile_name
andfile
.- Next, we create a request object
HttpEntity
and pass it insidepostForEntity
method ofRestTemplate
.
References
[1] https://spring.io/guides/gs/uploading-files/
[2] https://www.baeldung.com/spring-rest-template-multipart-upload