Want to accept file uploads in a Spring Boot app without inviting chaos or bad actors? This guide shows a tidy path to multipart file upload with Spring MVC and MultipartFile, how to validate and save files to disk, and how to test the whole thing like a responsible developer who likes backups.
User supplied filenames are delightful traps. They can overwrite things, carry sneaky paths, or just crash your dignity. Treat uploads like uninvited guests. Validate type, enforce size limits, and always build a safe filename on the server side.
In application properties configure limits and a folder for saved files. Examples of property names look like spring.servlet.multipart.max-file-size and spring.servlet.multipart.max-request-size. Also expose a custom property like file.upload-dir to point to a safe storage folder that your app can write to.
Keep your controller simple and mean. Accept a MultipartFile, run quick checks, then persist the file atomically. A common pattern is to:
@PostMapping("/upload")
public ResponseEntity upload(MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) {
return ResponseEntity.badRequest().body("No file provided")
}
String original = Paths.get(file.getOriginalFilename()).getFileName().toString()
String safeName = UUID.randomUUID().toString() + "_" + original
Path target = Paths.get(uploadDir).resolve(safeName).normalize()
// Optional content type check
String contentType = file.getContentType()
if (contentType == null || !allowedContentTypes.contains(contentType)) {
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body("Invalid file type")
}
// Save the file using transferTo or streaming for large files
file.transferTo(target.toFile())
return ResponseEntity.ok(Map.of("filename", safeName))
}
That sketch skips some Java punctuation so it reads better in prose. In real code keep try catch blocks and handle IO errors and security checks fully.
Use Postman or curl to send a multipart form data request to your upload endpoint. For curl use the form option and point to a local sample file. Confirm the response includes the saved filename and that the file appears in your configured folder.
File upload is simple when you treat it like plumbing. Configure multipart limits, validate early, sanitize names, and save safely. With a little discipline your Spring Boot file upload endpoint will behave and not ruin anyone's day. Now go build something that accepts photos not chaos.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.