3.6 Handling File Uploads (MultipartFile)
Learn how to handle image or document uploads in web applications using the MultipartFile interface and its related configurations.
1. How File Uploads Work (multipart/form-data)
Files are large binary data, not simple text. Therefore, they cannot be efficiently sent using application/json. For this purpose, HTTP uses a special encoding called multipart/form-data. In Spring, we receive this data using the MultipartFile interface.
2. File Upload Implementation Example
Controller Implementation
@RestController
@Slf4j
public class FileUploadController {
@PostMapping("/api/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return "File is empty.";
}
log.info("Filename: {}", file.getOriginalFilename());
log.info("File Size: {} bytes", file.getSize());
log.info("Content Type: {}", file.getContentType());
// Example: Saving to a local directory
String fullPath = "/uploads/" + file.getOriginalFilename();
file.transferTo(new File(fullPath));
return "Upload Success: " + fullPath;
}
}
3. Upload Capacity Configuration (application.yml)
Spring Boot has small default limits for file uploads. To allow large files, add the following to your application.yml:
spring:
servlet:
multipart:
max-file-size: 10MB # Max size for a single file
max-request-size: 50MB # Max total size for a single HTTP request
4. Practical Considerations
- Duplicate Filenames: Using the original filename directly can lead to overwriting existing files. It is safer to generate unique filenames using tools like
UUID. - Security: If an uploaded file is an executable script (.php, .sh, etc.), the server could be compromised. Always validate file extensions and perform security checks.
- Storage Choice: While saving to a local directory is fine initially, scaling a service usually requires switching to dedicated cloud storage like ** AWS S3**.