Spring MVC end to end series: 1. Maven and project layout · 2. DispatcherServlet and views · 3. Forms and validation · 4. Form login with Spring Security · 5. Sessions and remember-me · 6. File upload · 7. Cart and checkout · 8. Pagination and dynamic filters
Uploading an avatar or a product photo looks small, but it’s the place where strangers get to write arbitrary bytes onto your server. This post covers how an upload request is sent and received, where to store files, and a storage service that trusts nothing the client sends. The form holding the upload input is in part 3.
At a glance:
flowchart TD
A["Form multipart/form-data"] --> B["MultipartFile"]
B --> C{"Over 1MB or 10MB?"}
C -->|"Yes"| D["Catch MaxUploadSizeExceededException"]
C -->|"No"| E["Check magic bytes"]
E --> F["Generate UUID name"]
F --> G["Path stays inside root"]
G --> H["Write as a stream"]
H --> I["Object storage, DB keeps key"]
I -.->|"Rollback"| J["Clean orphan files"]
1. What an upload request looks like
Key idea: a normal form sends name=value&... and can’t carry binary bytes. multipart/form-data splits the body into parts, each with its own headers (field name, filename, type), separated by a boundary string.
POST /admin/users/5 HTTP/1.1
Content-Type: multipart/form-data; boundary=----X7a
------X7a
Content-Disposition: form-data; name="fullName"
Alice
------X7a
Content-Disposition: form-data; name="avatar"; filename="cat.png"
Content-Type: image/png
<file bytes>
------X7a--
On the form you only add enctype. Forget it and the browser sends just the file name as a string; the controller gets an empty MultipartFile or an error.
<form th:action="@{/admin/users/{id}(id=${user.id})}" th:object="${form}"
method="post" enctype="multipart/form-data">
<input th:field="*{fullName}">
<input type="file" name="avatar" accept="image/png,image/jpeg,image/webp">
<button>Save</button>
</form>
Spring Boot registers a StandardServletMultipartResolver, which uses the servlet container’s (Tomcat’s) built-in multipart parser. The DispatcherServlet parses the body before calling the controller, so inside the controller the file already sits on a temp disk location, and the text inputs still bind to the form DTO as usual.
MultipartFile |
Returns | Can you trust it? |
|---|---|---|
getOriginalFilename() |
the client-side filename | no: it can be ../../evil.jsp |
getContentType() |
the Content-Type the client declared |
no: anyone can write image/png |
getSize(), isEmpty() |
the actual size received | yes |
getInputStream() |
a stream over the content | yes, this is the real data |
getBytes() |
the whole file in one array | correct, but costs as much RAM as the file |
transferTo(Path) |
copies to another path | yes, but you must choose the path |
Multiple files and image preview in the browser
Several files in one input: add multiple, and the controller takes a List<MultipartFile>.
<input type="file" name="files" multiple accept="image/*">
@PostMapping("/products/{id}/images")
String upload(@PathVariable Long id, @RequestParam("files") List<MultipartFile> files) {
if (files.size() > 8) throw new InvalidFileException("at most 8 images");
List<String> keys = files.stream().filter(f -> !f.isEmpty())
.map(f -> storage.store(f, "product")).toList();
productService.addImages(id, keys);
return "redirect:/admin/products/" + id;
}
I tried two files of 1MB and 1.5MB: the controller got both, got 2 sizes=[1000000, 1500000]. Tomcat also limits the number of parts in one multipart request: Spring Boot 3.5 exposes server.tomcat.max-part-count, default 50 (text fields and files together).
Previewing an image before sending needs no server: URL.createObjectURL(file) creates a temporary URL pointing at the file inside the browser.
input.addEventListener('change', () => {
const f = input.files[0];
if (f) preview.src = URL.createObjectURL(f); // call URL.revokeObjectURL when done
});
Checking type and size in JavaScript only reports errors early; the server checks everything again.
2. Size limits
Key idea: set the limits in application.properties and catch MaxUploadSizeExceededException in a @ControllerAdvice. Without limits, one multi-gigabyte request fills the temp disk.
spring.servlet.multipart.max-file-size=2MB # per file, default 1MB
spring.servlet.multipart.max-request-size=10MB # whole request, default 10MB
@ExceptionHandler({InvalidFileException.class, MaxUploadSizeExceededException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
String badFile(Model m, Exception e) {
m.addAttribute("error", "Invalid file: " + e.getMessage());
return "error/page";
}
I ran the real app (embedded Tomcat, random port) with these limits: a 3MB file and an 11.4MB request of six 1.9MB files both got 400 with the error page from this handler. Without the handler the user sees the default 500 page.
3. Where to store files
Key idea: local disk is simplest but only fits a single server; the database is handy for transactions but bloats the DB; object storage is the default once you have several instances. Whatever you pick, the database only stores the file’s key.
| Local disk | BLOB column in the DB | Object storage (S3, MinIO) | |
|---|---|---|---|
| Setup | nothing | nothing | one more service |
| Several instances | no: files live on one machine (unless a shared volume) | yes | yes |
| Same transaction as the data | no | yes | no |
| Backup, replicas | separate backup | bigger DB backups, slower replicas | built in, with versioning |
| Serving to users | through the app or Nginx | always through the app, holding a DB connection | CDN or presigned URL, bypassing the app |
| Good for | demos, one server, network volume | small files that need strict consistency | most real systems |
The course says the database “holds up to about 4GB, for free”. True, MySQL’s LONGBLOB holds up to 4GB, but the cost is elsewhere: slower backups and restores, replicas copying every image byte, the buffer pool crowded by images instead of hot data, and a DB connection held for every image view.
4. Five bugs in the common way of saving uploads
Key idea: the course’s way of saving files works in the IDE, but has five bugs that show up on deployment or when someone tries to break it.
The course’s approach, condensed: take servletContext.getRealPath("/resources/images"), create a subfolder, name the file System.currentTimeMillis() + "-" + file.getOriginalFilename(), call file.getBytes() and write it through a manually opened and closed BufferedOutputStream.
The fifth bug is letting uploads live without any limit: no size limit, no type limit, no file-count limit (section 2).
5. A safe FileStorageService
Key idea: the service takes a MultipartFile and a subfolder name, checks the content by magic bytes, names the file with a UUID, checks the final path stays inside the root, writes with a stream, and returns a relative key to store in the database.
The steps of store(file, "avatar"):
- Reject an empty file or a folder name that isn’t
[a-z]+. - Read the first 12 bytes and detect the type; reject anything that isn’t PNG, JPEG or WebP.
- Key =
avatar/<uuid>.png, with the extension chosen by the server from the detected type. root.resolve(key).normalize(), then checkstartsWith(root).- Open a fresh stream and
Files.copyto the target. Return the key.
The test uploadStoresUnderRandomNameAndServesIt sends a real PNG named ../../evil.png: the key stored in the database matches avatar/[0-9a-f-]{36}\.png, and GET /files/<key> returns exactly those bytes.
Solution: the full FileStorageService
@ConfigurationProperties("app.upload")
public record StorageProperties(Path dir) {}
@Service
public class FileStorageService {
private static final Map<String, String> ALLOWED =
Map.of("image/png", ".png", "image/jpeg", ".jpg", "image/webp", ".webp");
private final Path root;
public FileStorageService(StorageProperties props) throws IOException {
this.root = props.dir().toAbsolutePath().normalize();
Files.createDirectories(root);
}
public String store(MultipartFile file, String folder) {
if (file.isEmpty()) throw new InvalidFileException("empty file");
if (!folder.matches("[a-z]+")) throw new InvalidFileException("bad folder");
String ext;
try (InputStream in = file.getInputStream()) {
String type = sniff(in.readNBytes(12));
ext = type == null ? null : ALLOWED.get(type); // Map.of(...).get(null) throws NPE
} catch (IOException e) { throw new UncheckedIOException(e); }
if (ext == null) throw new InvalidFileException("only png, jpeg, webp");
String key = folder + "/" + UUID.randomUUID() + ext;
Path target = root.resolve(key).normalize();
if (!target.startsWith(root)) throw new InvalidFileException("path traversal");
try {
Files.createDirectories(target.getParent());
try (InputStream in = file.getInputStream()) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) { throw new UncheckedIOException(e); }
return key;
}
public Path resolve(String key) {
Path p = root.resolve(key).normalize();
if (!p.startsWith(root)) throw new InvalidFileException("path traversal");
return p;
}
static String sniff(byte[] h) {
if (h.length >= 8 && (h[0] & 0xFF) == 0x89 && h[1] == 'P' && h[2] == 'N' && h[3] == 'G') return "image/png";
if (h.length >= 3 && (h[0] & 0xFF) == 0xFF && (h[1] & 0xFF) == 0xD8 && (h[2] & 0xFF) == 0xFF) return "image/jpeg";
if (h.length >= 12 && h[0] == 'R' && h[1] == 'I' && h[2] == 'F' && h[3] == 'F'
&& h[8] == 'W' && h[9] == 'E' && h[10] == 'B' && h[11] == 'P') return "image/webp";
return null;
}
}
application.properties: app.upload.dir=${java.io.tmpdir}/shop-uploads in the lab; production points to durable storage. getInputStream() is called twice: with StandardServletMultipartResolver each call opens a new stream over the temp file, so reading the header doesn’t eat the start of the file.
What a senior would add: cap the image’s pixel dimensions (a 2MB PNG can expand to a 30,000×30,000 image when decoded, a decompression bomb); re-encode the image with an imaging library to drop metadata (GPS location in EXIF) and any stray bytes appended after the image; put a FileStorage interface in front with LocalFileStorage and S3FileStorage implementations chosen by profile.
6. Serving files to viewers
Key idea: serve public images through a resource handler (or Nginx, a CDN); serve private files through a controller that checks permissions. Both must send the right Content-Type and X-Content-Type-Options: nosniff.
The lab registers a resource handler, without @EnableWebMvc so Spring Boot’s MVC configuration stays intact (part 2):
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations(props.dir().toAbsolutePath().toUri().toString());
}
Since the server picks the extension from the content, the Content-Type derived from it is correct. Spring Security sends nosniff by default, so the browser won’t “guess” an image into HTML.
Serving private files through a controller
Files like invoices or ID documents must not sit behind a public, guessable URL. A controller checks permissions, then streams:
@GetMapping("/orders/{id}/invoice")
ResponseEntity<Resource> invoice(@PathVariable Long id, @AuthenticationPrincipal ShopUserDetails me) {
Invoice inv = invoices.findOwned(id, me.id()) // 404 if it isn't yours
.orElseThrow(() -> new NotFoundException("invoice " + id));
Path file = storage.resolve(inv.fileKey());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment().filename("invoice-" + id + ".pdf").build().toString())
.header("X-Content-Type-Options", "nosniff")
.body(new FileSystemResource(file));
}
A FileSystemResource is streamed out rather than read into memory, and Range requests are supported. With object storage, the controller can redirect to a presigned GET URL that lives a few minutes instead of streaming itself.
7. Orphaned files when the transaction rolls back
Key idea: writing a file and writing the database are two systems with no shared transaction. A file written before a database rollback becomes garbage; a deleted row whose file stays is garbage too. Handle it with an after-commit callback plus a periodic cleanup job.
In the lab the controller stores the avatar before saving the user. If saving the user fails, the new file sits on disk with nothing pointing to it. Conversely, changing the avatar never deletes the old file.
@Transactional
public void changeAvatar(Long userId, MultipartFile file) {
AppUser u = users.findById(userId).orElseThrow();
String newKey = storage.store(file, "avatar");
String oldKey = u.getAvatar();
u.setAvatar(newKey);
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCompletion(int status) {
if (status == STATUS_ROLLED_BACK) storage.delete(newKey); // DB said no: drop new file
else if (oldKey != null) storage.delete(oldKey); // committed: drop old file
}
});
}
The callback doesn’t run if the process dies midway, so you still need a periodic job (cron jobs) that lists files older than a day that no database row points to, and deletes them. This changeAvatar snippet was not run in the lab.
Remember
- Can you explain why an upload form needs
multipart/form-data, and whatMultipartFiledoes and doesn’t tell you? - Can you list the five bugs of saving with
getRealPath+ original name +getBytes(), and the fix for each? - Do you know when to pick local disk, a DB BLOB, or object storage with presigned URLs?
- Do you know why user uploads can cause XSS and how to block it?
- Do you know how to clean up orphaned files after a database rollback?
Interview questions
Junior
What does a file upload form need that a normal form doesn’t?
method="post" and enctype="multipart/form-data"; the controller takes a MultipartFile (or List<MultipartFile> for several files).
Without enctype the browser sends x-www-form-urlencoded, which carries only the filename, not the content.
Why not use getOriginalFilename() as the filename on disk?
Because the client chose it: it can contain ../ to write outside the folder (path traversal), collide with another file, or contain odd characters.
The server generates the name (UUID) with an extension chosen from the content. The original name, if you need to display it, goes into its own database column.
Mid
How do you know an uploaded file really is an image?
Read the first few bytes (magic bytes) and compare them with the signatures of allowed types; don’t trust the extension or the client’s Content-Type.
More thorough: decode the image with an imaging library, check the pixel dimensions, then write a fresh image to strip metadata and stray data.
What happens in Spring Boot when an upload exceeds the limit, and how do you handle it?
Spring throws MaxUploadSizeExceededException while parsing the multipart body, before the controller runs; catch it in a @ControllerAdvice and return a 400 with a clear message.
The limits are spring.servlet.multipart.max-file-size (default 1MB) and max-request-size (default 10MB). A very large request may have its connection cut by Tomcat (max-swallow-size), so also limit it at the reverse proxy and in JavaScript.
How do getBytes() and getInputStream() differ when saving a file?
getBytes() loads the whole file into a heap array; getInputStream() lets you copy in chunks with roughly constant memory.
Many concurrent large uploads with getBytes() can easily cause OutOfMemoryError. Use Files.copy(in, target) or transferTo, and close streams with try-with-resources.
Senior
The app runs three instances behind a load balancer. Where should uploaded images go?
Object storage (S3, MinIO, GCS), with only the key in the database. Local disk doesn’t work because each instance sees only its own files.
Serve public images through a CDN, and private files through short-lived presigned URLs after a permission check. Large files can go up directly with a presigned PUT, followed by a scan once they arrive.
How can user-uploaded files cause XSS, and how do you stop it?
An SVG, HTML file or anything served with the wrong Content-Type gets opened by the browser as a page on your domain, and its script runs with the viewer’s cookies.
Stop it with: an allowlist checked by magic bytes, extension and Content-Type chosen by the server, nosniff, Content-Disposition: attachment for non-images, and serving user content from a separate cookieless domain.
The file was saved but the database transaction rolled back. What do you do with the file?
Register an afterCompletion callback: on rollback delete the new file, on commit delete the replaced old one; add a periodic job that removes files nothing points to.
The file system and the database don’t share a transaction, so the callback is best effort. The cleanup job uses an age threshold (say 24 hours) so it never deletes a file belonging to a request still in flight.
Useful phrases for interviews
- “A multipart request carries form fields and file bytes in separate parts, split by the boundary.”
- “I never use the client’s filename in the path; the server generates a UUID and picks the extension.”
- “I check the magic bytes instead of trusting the Content-Type header.”
- “We stream the upload to disk rather than calling getBytes, so memory stays flat.”
- “With three instances behind a load balancer, files go to object storage and the database keeps only the key.”
- “For large files the browser uploads straight to S3 with a presigned URL, and we scan them afterwards.”
- “An uploaded SVG served from our own domain is a stored XSS, so user content lives on a separate domain.”
- “A rollback after the write leaves an orphaned file, so we clean up after completion and with a nightly job.”
Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.