java
42 lines · 10 steps
Handling secure file uploads in Spring
A Spring REST endpoint that validates, safely renames, and stores multipart uploads while guarding against path traversal.
Explained by
highlit
1@RestController
2@RequestMapping("/api/files")
3public class FileUploadController {
4
5 private static final Path UPLOAD_DIR = Paths.get("uploads");
6 private static final Set<String> ALLOWED_TYPES = Set.of("image/png", "image/jpeg", "application/pdf");
7
8 @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
9 public ResponseEntity<UploadResponse> upload(@RequestParam("file") MultipartFile file) throws IOException {
10 if (file.isEmpty()) {
11 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "File is empty");
12 }
13 if (!ALLOWED_TYPES.contains(file.getContentType())) {
14 throw new ResponseStatusException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "Unsupported file type");
15 }
16
17 Files.createDirectories(UPLOAD_DIR);
18
19 String original = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
20 String extension = StringUtils.getFilenameExtension(original);
21 String storedName = UUID.randomUUID() + (extension != null ? "." + extension : "");
22 Path target = UPLOAD_DIR.resolve(storedName).normalize();
23
24 if (!target.startsWith(UPLOAD_DIR)) {
25 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid file path");
26 }
27
28 try (InputStream in = file.getInputStream()) {
29 Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
30 }
31
32 URI location = ServletUriComponentsBuilder.fromCurrentRequest()
33 .path("/{name}")
34 .buildAndExpand(storedName)
35 .toUri();
36
37 return ResponseEntity.created(location)
38 .body(new UploadResponse(storedName, original, file.getSize()));
39 }
40
41 public record UploadResponse(String storedName, String originalName, long size) {}
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Validate uploads on both emptiness and content type before touching the filesystem.
- 2Generate server-side filenames and normalize paths to defend against path traversal attacks.
- 3Return 201 Created with a Location header so clients can immediately reference the stored resource.
Related explainers
java
@Component public class HeaderMergeFilter { private static final String PER_REQUEST_HEADERS = HeaderMergeFilter.class.getName() + ".headers";
Merging default and per-request headers in Spring
webclient
filters
http-headers
Intermediate
8 steps
java
import java.util.HashSet; import java.util.Set; public final class CollectionDiff<T> {
Diffing two collections with set operations
set-operations
immutability
generics
Intermediate
8 steps
go
package handlers import ( "encoding/base64"
Cursor pagination in a Gin handler
pagination
cursor
rest-api
Intermediate
8 steps
java
public record AppConfig( String host, int port, String databaseUrl,
Loading typed config from env vars in Java
records
configuration
environment-variables
Intermediate
6 steps
typescript
export function isValidCardNumber(input: string): boolean { const digits = input.replace(/[\s-]/g, ""); if (!/^\d{12,19}$/.test(digits)) {
Validating card numbers with the Luhn check
luhn-algorithm
checksum
input-validation
Intermediate
7 steps
java
public class RequestThrottler { private final Semaphore permits; private final long acquireTimeoutMillis;
Bounding concurrency with a Semaphore in Java
concurrency
semaphore
rate-limiting
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/handling-secure-file-uploads-in-spring-explained-java-987b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.