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
package com.example.fs; import java.io.IOException; import java.nio.file.FileSystems;
Watching a directory with Java NIO
file-io
event-loop
resource-management
Intermediate
8 steps
java
public final class QueryParams { private final Map<String, List<String>> params;
Parsing and building URL query strings in Java
parsing
multimap
url-encoding
Intermediate
9 steps
java
public final class ShippingAddress { private final String recipient; private final String line1; private final String line2;
Building immutable objects with the Builder pattern
builder-pattern
immutability
validation
Intermediate
7 steps
java
import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter;
Converting timestamps across time zones in Java
date-time
time-zones
instant
Intermediate
6 steps
rust
use axum::{extract::Multipart, http::StatusCode, Json}; use serde::Serialize; use tokio::io::AsyncWriteExt; use uuid::Uuid;
Streaming multipart uploads in Axum
multipart
streaming
async-io
Intermediate
10 steps
java
package com.example.payments.config; import com.stripe.StripeClient; import org.springframework.beans.factory.annotation.Value;
Swapping payment gateways by profile in Spring
dependency-injection
profiles
configuration
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.