Simple Spring Boot File Upload Example |Video upload date:  · Duration: PT12M5S  · Language: EN

Compact guide to add multipart file upload to a Spring Boot app with controller storage and quick testing tips

Short version that does not waste your time

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.

Why you should not trust filenames and user input

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.

What you need in your project

  • Spring Boot web starter such as spring-boot-starter-web to bring Spring MVC and servlet multipart support
  • Properties in application properties or yaml for multipart limits and a storage path such as spring.servlet.multipart.max-file-size and spring.servlet.multipart.max-request-size and a custom upload folder setting
  • Controller that accepts MultipartFile and a storage helper

Configuration tips that will save your weekend

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.

Controller design notes

Keep your controller simple and mean. Accept a MultipartFile, run quick checks, then persist the file atomically. A common pattern is to:

  • Reject empty uploads
  • Reject files that exceed configured limits
  • Optionally check content type against an allow list
  • Produce a safe filename using a UUID prefix and a sanitized original name

Example handler sketch

@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.

Storage hygiene and safety checklist

  • Never trust the original filename to determine storage paths
  • Use a UUID or timestamp prefix to avoid collisions and accidental overwrites
  • Validate file size against spring.servlet.multipart settings to avoid memory or disk exhaustion
  • Keep uploads outside of static resource folders unless you really want them to be public
  • Scan or otherwise validate files if you accept executable or archive content

Testing the upload endpoint

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.

Common gotchas and how to avoid them

  • Overwriting files when two uploads share a name. Fix this with UUIDs or per user folders
  • Wrong content type reported by browsers. Rely on server side checks and validation not just the reported MIME type
  • Large files blowing up memory. Use streaming APIs or increase multipart limits carefully and monitor disk usage

Parting advice

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.