Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 66 ยท Building REST APIs

File Uploads, Downloads and Static Resources

Handle files safely in Spring Boot: MultipartFile uploads, size limits, content type checks, path traversal defense, Resource downloads and static content.

Sooner or later an application has to accept a file: a profile photo, a CSV import, a PDF invoice. It also has to give files back, and serve its own CSS, images and JavaScript. Spring Boot handles all of this with a few types and a handful of properties. The code is short; the dangers are not. A file upload is user input in its most hostile form: the name, the type and the size are all chosen by the sender.

This lesson covers receiving a MultipartFile, limiting its size, deciding what it really is, storing it without letting the user choose the path, sending files back with a Resource, and how Boot serves static content. If you have not met controllers yet, start with REST Controllers.

Spring Boot cannot run on this site, so the controller code is read-only. The runnable stand-ins check file names, paths and content types in plain Java, which is where the real security work happens anyway.

Receiving an upload

Browsers send files in a multipart/form-data request: one body with several parts, each with its own headers. Spring parses the request and gives each file part to you as a MultipartFile.

Java
@RestController
@RequestMapping("/files")
class FileController {

    private final FileStorage storage;

    FileController(FileStorage storage) {
        this.storage = storage;
    }

    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    ResponseEntity<StoredFile> upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().build();
        }
        StoredFile stored = storage.save(file);
        return ResponseEntity.created(URI.create("/files/" + stored.id())).body(stored);
    }
}

MultipartFile gives you getOriginalFilename(), getContentType(), getSize(), getInputStream() and transferTo(Path). Several files in one field arrive as List<MultipartFile>. A file together with a JSON part can be received with @RequestPart.

Remember the golden rule: everything the client sends about the file is a claim, not a fact. The file name, the content type header and even the extension can be anything.

Limiting the size

Without limits, one request could fill your disk or memory. Boot sets modest defaults (1 MB per file, 10 MB per request) and you adjust them in application.yml:

YAML
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 12MB
      file-size-threshold: 1MB

file-size-threshold is the size above which uploaded data is written to a temporary file instead of being kept in memory. When a request is over the limit, Spring raises a MaxUploadSizeExceededException; handle it in your exception advice and answer 413 Payload Too Large with a clear message (see Error Handling and Problem Details).

Two further limits sit in front of your code:

  • The embedded server has its own settings, for example server.tomcat.max-swallow-size, which decides how much of an oversized body Tomcat reads and discards before answering.
  • A reverse proxy such as nginx has its own body size limit (client_max_body_size). If you get a 413 from nginx and your app never logs the request, that is why.

Never trust the sender

Name May contain ../ or odd symbols.
Content type A header the client can fake.
Size Can be far bigger than you expect.
Bytes The only honest evidence.
1 / 2

Safe names and path traversal

The most famous upload bug is path traversal. If your code writes to uploadDir + "/" + file.getOriginalFilename(), a client can send the name ../../etc/cron.d/job or ..\..\app\config.yml and escape the upload folder. The original name is only ever a label to show to people.

Two defenses work together:

  1. Generate the stored name yourself (a random UUID, plus a safe extension if needed) and keep the original name in the database for display.
  2. Resolve, normalize and verify. Build the target path, call normalize(), and check that the result still starts with your base directory.
Java
@Component
class FileStorage {

    private final Path root;

    FileStorage(@Value("${app.upload-dir}") Path root) throws IOException {
        this.root = Files.createDirectories(root.toAbsolutePath().normalize());
    }

    StoredFile save(MultipartFile file) throws IOException {
        String id = UUID.randomUUID().toString();
        Path target = root.resolve(id).normalize();
        if (!target.startsWith(root)) {
            throw new IllegalStateException("Path escapes the upload directory");
        }
        try (InputStream in = file.getInputStream()) {
            Files.copy(in, target);            // streams; never loads the whole file
        }
        return new StoredFile(id, file.getOriginalFilename(), file.getSize());
    }
}

Using Files.copy with an InputStream streams the data in small chunks, so a 500 MB file does not need 500 MB of heap. Never call file.getBytes() on files you do not control the size of.

The check is easy to get subtly wrong, so it helps to see it run. This stand-in cleans a name and verifies the resolved path against a base folder.

Java Safe file names and path checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at /etc/passwd: resolve with an absolute path returns that absolute path, and the startsWith check catches it. That is why you verify the result, not the input text. Cleaning the name is a second layer for names you intend to keep; generating the name is the better first layer.

Content type and what the file really is

file.getContentType() is whatever the browser sent in the part header. A script can claim image/png for a Windows executable. To know what a file is, look at its first bytes, the magic number: PNG files start with 89 50 4E 47, JPEG with FF D8 FF, PDF with %PDF, ZIP (and DOCX, JAR) with PK.

For stronger checks use a library that detects types by content, such as Apache Tika, and keep an allow-list of accepted types rather than a block-list of bad ones. Also remember that an allowed type can still be dangerous when delivered wrongly: an SVG or HTML file served from your own origin can run scripts in your users' browsers.

Java Sniffing the real type and enforcing size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each rejection comes from the bytes and the size, never from the claimed type. In a real controller you would read only the first few bytes from the stream for the sniff step, then continue streaming the rest to disk.

Sending files back

To download, return a Resource. Spring streams it to the client, handles Range requests for large files and sets the length for you.

Java
@GetMapping("/{id}")
ResponseEntity<Resource> download(@PathVariable String id) throws IOException {
    StoredFile meta = storage.find(id);                 // from the database
    Path path = storage.pathOf(id);                      // validated, inside root
    Resource body = new UrlResource(path.toUri());

    return ResponseEntity.ok()
        .contentType(MediaType.parseMediaType(meta.contentType()))
        .contentLength(meta.size())
        .header(HttpHeaders.CONTENT_DISPOSITION,
            ContentDisposition.attachment().filename(meta.originalName()).build().toString())
        .header("X-Content-Type-Options", "nosniff")
        .body(body);
}
  • ContentDisposition.attachment() makes browsers download instead of rendering. For user-supplied files this is the safe default, and it encodes odd characters in the name correctly.
  • X-Content-Type-Options: nosniff stops browsers from guessing a different type than the one you declared.
  • The id in the URL is looked up in your database. Never take a path from the URL and open it directly; that is path traversal again, in the other direction.
  • Use StreamingResponseBody when you generate a large response on the fly, such as a CSV export, so it never sits fully in memory.

Static resources

Static files such as CSS, JavaScript, images and a favicon.ico need no controller. Boot serves anything under these classpath folders, checked in this order: /META-INF/resources/, /resources/, /static/ and /public/. In practice, src/main/resources/static is where files go, so static/css/site.css is available at /css/site.css.

YAML
spring:
  web:
    resources:
      cache:
        cachecontrol:
          max-age: 365d
      chain:
        strategy:
          content:
            enabled: true
            paths: /**

The content strategy adds a hash of the file to its URL (for example /css/site-3f9a1c.css) when you link it through a Spring-aware helper such as Thymeleaf's @{/css/site.css}. Because the URL changes whenever the file changes, you can safely cache it for a year.

Two cautions about static content:

  • Files inside the jar are read-only and change only on deploy. Uploaded files do not belong there; serve them from a controller (or from object storage with signed URLs, which scales much better than your app server).
  • With Spring Security enabled, the static folders are open by default, but your own authorizeHttpRequests rules still apply to everything else. See Spring Security Fundamentals.

If you map an extra folder with spring.web.resources.static-locations, remember that you replace the defaults unless you list them again. Never point it at a folder that contains anything private.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is storing an upload under uploadDir + "/" + file.getOriginalFilename() dangerous?

    The original file name is chosen by the client. Names containing .. segments can point outside the upload folder, so generate the stored name yourself and verify the normalized path.
  2. 2. Which property limits the size of one uploaded file in Spring Boot?

    spring.servlet.multipart.max-file-size caps a single file and max-request-size caps the whole request. Exceeding them raises MaxUploadSizeExceededException.
  3. 3. What is the most reliable way to find out what type an uploaded file really is?

    Header, extension and name are all supplied by the client. The leading bytes of the file are far harder to fake while keeping the file valid.
  4. 4. Why do downloads of user-supplied files usually use Content-Disposition: attachment?

    Rendering an uploaded HTML or SVG file from your own origin can run attacker scripts. Forcing a download, plus nosniff, removes that risk.
  5. 5. Where does Spring Boot look for static files by default?

    Boot serves content from those classpath locations with no controller needed; src/main/resources/static is the usual place.

Summary

  • Uploads arrive as multipart/form-data; Spring gives you each file as a MultipartFile.
  • Set spring.servlet.multipart.max-file-size and max-request-size, and remember that the server and any proxy have limits of their own.
  • File name, content type and extension are claims from the client; generate stored names yourself and verify that the normalized path stays inside your base directory.
  • Check the real type from the first bytes (or with a detection library) against an allow-list.
  • Stream with Files.copy and Resource; avoid getBytes() on untrusted sizes.
  • Send user files with Content-Disposition: attachment and nosniff.
  • Static files live under static/, are served without code and can be cached for long with content-hash URLs; uploads belong in storage outside the jar.

Next: DataSource, Connection Pools and JdbcClient.