Video in progress
How do you accept a file upload (MultipartFile) in a controller?
The request is multipart/form-data, and in the controller you take a MultipartFile parameter with @RequestParam or @RequestPart. The size limit is configured in spring.servlet.multipart.
📖 Answer
@PostMapping(path = "/avatars", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("fayl bo'sh");
}
String name = UUID.randomUUID() + ".png"; // we don't use the name the user gave
file.transferTo(Path.of("/data/avatars", name));
return ResponseEntity.ok(name);
}
spring:
servlet:
multipart:
max-file-size: 5MB # default 1MB
max-request-size: 10MB # default 10MB
If the limit is exceeded, MaxUploadSizeExceededException is thrown. Catch it in a @RestControllerAdvice and return 413 or a clear message.
Security:
- don't append
file.getOriginalFilename()directly to a path: a name like../../etc/passwdcan arrive; getContentType()is a value the client sent and can't be trusted; if needed, check the bytes at the start of the file;- don't read big files fully into memory with
getBytes(); usegetInputStream()ortransferTo.
Sign up to mark studied questions and save your progress.