Spring Boot file upload and download: MultipartFile, limits and safe storage

Uploading a file to Spring Boot takes one MultipartFile parameter, but the request format, the limits enforced by Tomcat and the file name chosen by the client all affect what happens. This page shows a multipart request on the wire, then runs uploads with JSON metadata, every size and count limit, safe storage against path traversal, and downloads with Unicode names and byte ranges.

Contents

How a file upload reaches a controller

A browser or HTTP client uploads files with a multipart/form-data request. The body is split into parts, separated by a boundary string that the client picks and announces in the Content-Type header. Each part has its own small header block: a Content-Disposition line with the form field's name, a filename for file parts, and usually a Content-Type. Text fields and files travel in the same request.

In a Spring Boot application with Tomcat, the work is split between the server and Spring:

  1. Tomcat parses the multipart body using the Servlet API's Part support. It writes each part to a temporary file, or keeps it in memory if it is smaller than the threshold, and enforces the size and count limits.
  2. Spring's StandardServletMultipartResolver, which Spring Boot registers, wraps the request in a MultipartHttpServletRequest before the controller is called.
  3. Argument resolvers hand the parts to the controller method: @RequestParam MultipartFile for files, @RequestParam String for text fields, and @RequestPart for parts that should be converted, such as JSON.
  4. After the response is written, Spring deletes the temporary files. A file that must be kept has to be copied somewhere during the request.

Spring Boot configures the limits with spring.servlet.multipart.* properties, read from the jar's configuration metadata for Spring Boot 4.1:

Multipart settings and their defaults
PropertyDefaultMeaning
spring.servlet.multipart.max-file-size1MBLargest single file
spring.servlet.multipart.max-request-size10MBLargest whole request, all parts together
spring.servlet.multipart.file-size-threshold0BParts larger than this are written to disk; 0 writes every part to disk
spring.servlet.multipart.locationThe server's temporary directoryWhere Tomcat writes the parts
spring.servlet.multipart.resolve-lazilyfalseParse the parts only when the controller first asks for them
server.tomcat.max-part-count50Most parts in one request, text fields included
server.tomcat.max-swallow-size2MBHow much of a rejected body Tomcat reads before closing the connection

The examples use Spring Boot 4.1 with Spring Framework 7.0 and only spring-boot-starter-webmvc. Each starts the application on a random port, uploads or downloads from the same program, and shuts down.

A single file, and what goes over the wire

A CSV export with a comment field is a typical form: one file and one text field. The program builds the multipart body by hand with a fixed boundary, so that you can see exactly what a client sends, then posts it with the JDK's HttpClient:

Java
package demo.single;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@SpringBootApplication
public class SingleUpload {

    public record Received(String field, String originalFilename, String contentType,
                           long size, String firstLine, String comment) {}

    @RestController
    static class UploadController {
        @PostMapping("/upload")
        public Received upload(@RequestParam("file") MultipartFile file,
                               @RequestParam String comment) throws Exception {
            String text = new String(file.getBytes(), StandardCharsets.UTF_8);
            return new Received(file.getName(), file.getOriginalFilename(),
                    file.getContentType(), file.getSize(), text.lines().findFirst().orElse(""),
                    comment);
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(SingleUpload.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();

            String boundary = "----demo-boundary-7MA4YWxk";
            String body = "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"comment\"\r\n"
                    + "\r\n"
                    + "monthly export\r\n"
                    + "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"file\"; filename=\"sales.csv\"\r\n"
                    + "Content-Type: text/csv\r\n"
                    + "\r\n"
                    + "region,total\nnorth,1200\nsouth,950\n\r\n"
                    + "--" + boundary + "--\r\n";
            System.out.println("Request body as sent (CRLF shown as line breaks):");
            System.out.println(body.replace("\r\n", "\n").strip());

            HttpRequest request = HttpRequest.newBuilder(
                            URI.create("http://localhost:" + port + "/upload"))
                    .header("Content-Type", "multipart/form-data; boundary=" + boundary)
                    .POST(BodyPublishers.ofString(body))
                    .build();
            HttpResponse<String> response = HttpClient.newHttpClient()
                    .send(request, BodyHandlers.ofString());
            System.out.println();
            System.out.println("Response " + response.statusCode() + ":");
            System.out.println(response.body());
        }
    }
}
Output
Request body as sent (CRLF shown as line breaks):
------demo-boundary-7MA4YWxk
Content-Disposition: form-data; name="comment"

monthly export
------demo-boundary-7MA4YWxk
Content-Disposition: form-data; name="file"; filename="sales.csv"
Content-Type: text/csv

region,total
north,1200
south,950

------demo-boundary-7MA4YWxk--

Response 200:
{"field":"file","originalFilename":"sales.csv","contentType":"text/csv","size":34,"firstLine":"region,total","comment":"monthly export"}
  • The body has two parts between the boundary lines, and ends with the boundary followed by --. Line ends in multipart are CRLF; the program prints them as plain line breaks.
  • file.getName() is file, the form field name, while getOriginalFilename() is sales.csv, the name the client sent. Both come from the part's Content-Disposition header.
  • getContentType() is text/csv, taken from the part's header. The client chooses it, so it says what the client claims, not what the file contains.
  • getSize() is 34: the 34 bytes of CSV text, without the CRLF that ends the part, which belongs to the boundary.
  • The text field arrived through @RequestParam String comment, in the same way as a query parameter.

getBytes() loads the whole file into memory, which is fine for small files like this. For large files, use getInputStream() or transferTo(Path), which stream from the temporary file.

Several files with JSON metadata

A photo album upload needs structured data next to the files: a title and a list of tags. Sending them as one JSON part keeps the form flexible. This program sends the request with Spring's RestClient and MultipartBodyBuilder, which write the boundaries and part headers for you:

Java
package demo.multi;

import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import org.springframework.web.multipart.MultipartFile;

@SpringBootApplication
public class FilesAndJson {

    public record Album(String title, List<String> tags) {}

    public record Saved(String title, List<String> tags, List<String> photos) {}

    @RestController
    static class AlbumController {
        @PostMapping(path = "/albums", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        public Saved create(@RequestPart("album") Album album,
                            @RequestPart("photos") List<MultipartFile> photos) {
            List<String> names = photos.stream()
                    .map(p -> p.getOriginalFilename() + " (" + p.getSize() + " bytes, "
                            + p.getContentType() + ")")
                    .toList();
            return new Saved(album.title(), album.tags(), names);
        }
    }

    public static void main(String[] args) {
        try (var context = new SpringApplicationBuilder(FilesAndJson.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            RestClient client = RestClient.create("http://localhost:" + port);

            MultipartBodyBuilder parts = new MultipartBodyBuilder();
            parts.part("album", new Album("Lisbon 2026", List.of("travel", "city")),
                       MediaType.APPLICATION_JSON);
            parts.part("photos", new ByteArrayResource(new byte[2048]))
                 .filename("tram.jpg").contentType(MediaType.IMAGE_JPEG);
            parts.part("photos", new ByteArrayResource(new byte[3072]))
                 .filename("river.png").contentType(MediaType.IMAGE_PNG);

            String response = client.post().uri("/albums")
                    .contentType(MediaType.MULTIPART_FORM_DATA)
                    .body(parts.build())
                    .retrieve()
                    .body(String.class);
            System.out.println(response);
        }
    }
}
Output
{"title":"Lisbon 2026","tags":["travel","city"],"photos":["tram.jpg (2048 bytes, image/jpeg)","river.png (3072 bytes, image/png)"]}
  • @RequestPart("album") Album album received a record. Unlike @RequestParam, @RequestPart converts the part with a message converter chosen from the part's own Content-Type, here application/json, so the Jackson converter read it.
  • Two parts named photos became a List<MultipartFile> of two files, in the order they were sent. An array, MultipartFile[], works the same way.
  • Each file kept its own name, size and content type: tram.jpg with 2048 bytes as image/jpeg, and river.png with 3072 bytes as image/png.

A plain HTML form cannot set a content type on a part, so for browser forms it is simpler to send the metadata as ordinary text fields and read them with @RequestParam.

Size and count limits

Limits protect the server from uploads that would fill its disk or memory. The limits here are set to 100 KB per file and 250 KB per request, so small byte arrays can cross them. The last request stays far below both sizes, but sends many parts:

Java
package demo.limits;

import java.util.Arrays;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.RestClient;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

@SpringBootApplication
public class SizeLimits {

    @RestController
    static class UploadController {
        @PostMapping("/upload")
        public String upload(@RequestParam("file") MultipartFile[] files) {
            long total = 0;
            for (MultipartFile f : files) {
                total += f.getSize();
            }
            return files.length + " file(s), " + total + " bytes";
        }
    }

    @RestControllerAdvice
    static class UploadErrors {
        @ExceptionHandler
        public ProblemDetail tooLarge(MaxUploadSizeExceededException e) {
            ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                    HttpStatus.CONTENT_TOO_LARGE, "Upload exceeds a configured limit");
            problem.setProperty("cause", e.getMostSpecificCause().getClass().getSimpleName());
            return problem;
        }
    }

    static RestClient client;

    static void upload(String label, int... sizes) {
        MultipartBodyBuilder parts = new MultipartBodyBuilder();
        for (int i = 0; i < sizes.length; i++) {
            parts.part("file", new ByteArrayResource(new byte[sizes[i]]))
                 .filename("part" + i + ".bin");
        }
        String result = client.post().uri("/upload")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(parts.build())
                .exchange((request, response) -> response.getStatusCode().value() + " "
                        + response.bodyTo(String.class));
        System.out.println(label + " -> " + result);
    }

    public static void main(String[] args) {
        try (var context = new SpringApplicationBuilder(SizeLimits.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN",
                            "spring.servlet.multipart.max-file-size=100KB",
                            "spring.servlet.multipart.max-request-size=250KB")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            client = RestClient.create("http://localhost:" + port);

            upload("one 80 KB file", 80000);
            upload("two 80 KB files", 80000, 80000);
            upload("one 120 KB file", 120000);
            upload("three 90 KB files", 90000, 90000, 90000);
            int[] many = new int[60];
            Arrays.fill(many, 10);
            upload("sixty 10-byte files", many);
        }
    }
}
Output
one 80 KB file -> 200 1 file(s), 80000 bytes
two 80 KB files -> 200 2 file(s), 160000 bytes
one 120 KB file -> 413 {"detail":"Upload exceeds a configured limit","instance":"/upload","status":413,"title":"Content Too Large","cause":"FileSizeLimitExceededException"}
three 90 KB files -> 413 {"detail":"Upload exceeds a configured limit","instance":"/upload","status":413,"title":"Content Too Large","cause":"SizeLimitExceededException"}
sixty 10-byte files -> 413 {"detail":"Upload exceeds a configured limit","instance":"/upload","status":413,"title":"Content Too Large","cause":"FileCountLimitExceededException"}
  • One 80 KB file and two 80 KB files were accepted: each file is under 100 KB, and 160,000 bytes in total is under 250 KB.
  • One 120 KB file broke max-file-size. Tomcat threw FileSizeLimitExceededException, and Spring wrapped it in MaxUploadSizeExceededException.
  • Three 90 KB files are each allowed, but 270,000 bytes broke max-request-size. The cause was SizeLimitExceededException.
  • Sixty files of 10 bytes broke a limit that has nothing to do with size: server.tomcat.max-part-count, which is 50 by default. The cause was FileCountLimitExceededException. Forms with many small files or fields hit this limit in production, so raise it when your forms need more.
  • All three failures reached the @ExceptionHandler as MaxUploadSizeExceededException, which the handler turned into 413. HttpStatus.CONTENT_TOO_LARGE is the RFC 9110 name for 413; the older PAYLOAD_TOO_LARGE is deprecated since Spring Framework 7.0.

The exception is thrown while the request is parsed, before the controller method runs, so a try block in the controller cannot catch it. Use an advice as here. For very large rejected uploads, Tomcat reads at most server.tomcat.max-swallow-size of the remaining body and then closes the connection, so a client may see a connection reset instead of the 413. Set limits from what your application expects, and put a matching limit in any proxy in front of it.

Storing uploads safely

An upload endpoint accepts files from strangers, and both the file name and the content type are whatever the client chose to send. The program sends a file name with ../, a script that claims to be a PNG image, and a Windows path, to an endpoint that trusts the name and to one that does not:

Java
package demo.storage;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import org.springframework.web.multipart.MultipartFile;

@SpringBootApplication
public class SafeStorage {

    static Path root;   // the upload directory

    @RestController
    static class AvatarController {
        private final AtomicInteger counter = new AtomicInteger();

        @PostMapping("/naive")
        public String naive(@RequestParam MultipartFile file) throws IOException {
            Path target = root.resolve(file.getOriginalFilename());   // trusts the client
            return "would write to " + root.relativize(target.normalize())
                    + ", inside upload dir = " + target.normalize().startsWith(root);
        }

        @PostMapping("/avatars")
        public ResponseEntity<String> avatar(@RequestParam MultipartFile file)
                throws IOException {
            String declared = file.getContentType();
            byte[] head;
            try (InputStream in = file.getInputStream()) {
                head = in.readNBytes(8);
            }
            boolean png = Arrays.equals(head, HexFormat.of().parseHex("89504e470d0a1a0a"));
            if (!png) {
                return ResponseEntity.unprocessableContent()
                        .body("rejected: declared " + declared + ", but content is not PNG");
            }
            String cleaned = StringUtils.cleanPath(file.getOriginalFilename());
            String original = StringUtils.getFilename(cleaned);   // last segment only
            String stored = "avatar-" + counter.incrementAndGet() + ".png";
            Path target = root.resolve(stored);
            try (InputStream in = file.getInputStream()) {
                Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
            }
            return ResponseEntity.ok("stored " + original + " as " + stored + " ("
                    + Files.size(target) + " bytes)");
        }
    }

    static RestClient client;

    static void send(String path, String filename, String type, byte[] content) {
        MultipartBodyBuilder parts = new MultipartBodyBuilder();
        parts.part("file", new ByteArrayResource(content))
             .filename(filename).contentType(MediaType.parseMediaType(type));
        String result = client.post().uri(path)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(parts.build())
                .exchange((request, response) -> response.getStatusCode().value() + " "
                        + response.bodyTo(String.class));
        System.out.println("POST " + path + " filename=\"" + filename + "\" " + type);
        System.out.println("  " + result);
    }

    public static void main(String[] args) throws IOException {
        root = Files.createTempDirectory("uploads").toRealPath();
        try (var context = new SpringApplicationBuilder(SafeStorage.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            client = RestClient.create("http://localhost:" + port);

            byte[] png = HexFormat.of().parseHex("89504e470d0a1a0a0000000d49484452");
            byte[] script = "#!/bin/sh\nrm -rf ~\n".getBytes();

            send("/naive", "../../home/app/.bashrc", "text/plain", script);
            send("/avatars", "me.png", "image/png", png);
            send("/avatars", "cat.png", "image/png", script);
            send("/avatars", "C:\\Users\\ana\\photos\\..\\me.png", "image/png", png);
        } finally {
            FileSystemUtils.deleteRecursively(root);
        }
    }
}
Output
POST /naive filename="../../home/app/.bashrc" text/plain
  200 would write to ../../home/app/.bashrc, inside upload dir = false
POST /avatars filename="me.png" image/png
  200 stored me.png as avatar-1.png (16 bytes)
POST /avatars filename="cat.png" image/png
  422 rejected: declared image/png, but content is not PNG
POST /avatars filename="C:\Users\ana\photos\..\me.png" image/png
  200 stored me.png as avatar-2.png (16 bytes)
  • The naive endpoint resolved ../../home/app/.bashrc against the upload directory and would have written two levels above it. getOriginalFilename() returned the name exactly as the client sent it, path and all. This is a path traversal attack, and it lets a client overwrite any file the application can write.
  • The safe endpoint never uses the client's name for the file on disk. It stores avatar-1.png, a name it generated, and keeps the original name only as data to show or store in a database.
  • cat.png was declared image/png but was rejected with 422, because its first eight bytes are not the PNG signature 89 50 4E 47 0D 0A 1A 0A. Checking the content itself, not the declared type, stops files that only pretend to be images.
  • The Windows path C:\Users\ana\photos\..\me.png became me.png. StringUtils.cleanPath turned the backslashes into slashes and removed the .. step, and StringUtils.getFilename kept the last segment. Some older browsers send full paths like this.

Other rules for real systems follow from the same idea:

  • Location: store uploads outside the directories that the application serves as static content, so an uploaded HTML or script file can never be requested and run.
  • Content checks: for images, decoding the file with an image library is a stronger check than the signature. For documents, a virus scanner may be required.
  • Copying: Files.copy(file.getInputStream(), target) or file.transferTo(target) stream the data without loading it into memory. Do this during the request, since the temporary file is deleted afterwards.
  • Object storage: for files that many servers must read, store them in an object store such as Amazon S3, and keep only the key in the database.

Downloads, file names and ranges

A download endpoint has the opposite problems: the browser needs a file name, which may not be ASCII, and clients such as video players or download managers ask for parts of the file. A 36-byte report with the name Résumé März.txt shows both:

Java
package demo.download;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class FileDownload {

    static final byte[] REPORT = "0123456789abcdefghijklmnopqrstuvwxyz"
            .getBytes(StandardCharsets.US_ASCII);

    @RestController
    static class ReportController {
        @GetMapping("/reports/latest")
        public ResponseEntity<Resource> latest() {
            ContentDisposition disposition = ContentDisposition.attachment()
                    .filename("Résumé März.txt", StandardCharsets.UTF_8)
                    .build();
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString())
                    .contentType(MediaType.TEXT_PLAIN)
                    .body(new ByteArrayResource(REPORT));
        }
    }

    static void get(String base, String range) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/reports/latest"));
        if (range != null) {
            request.header("Range", range);
        }
        HttpResponse<String> r = HttpClient.newHttpClient()
                .send(request.build(), BodyHandlers.ofString());
        System.out.println("GET /reports/latest" + (range == null ? "" : ", Range: " + range)
                + " -> " + r.statusCode());
        for (String h : new String[] {"Content-Disposition", "Content-Type", "Content-Length",
                                      "Accept-Ranges", "Content-Range"}) {
            r.headers().firstValue(h).ifPresent(v -> System.out.println("  " + h + ": " + v));
        }
        System.out.println("  body: " + r.body().replace("\r\n", "|"));
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(FileDownload.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String base = "http://localhost:" + port;
            get(base, null);
            get(base, "bytes=10-15");
            get(base, "bytes=-6");
        }
    }
}
Output
GET /reports/latest -> 200
  Content-Disposition: attachment; filename="Resume Maerz.txt"; filename*=UTF-8''R%C3%A9sum%C3%A9%20M%C3%A4rz.txt
  Content-Type: text/plain
  Content-Length: 36
  Accept-Ranges: bytes
  body: 0123456789abcdefghijklmnopqrstuvwxyz
GET /reports/latest, Range: bytes=10-15 -> 206
  Content-Disposition: attachment; filename="Resume Maerz.txt"; filename*=UTF-8''R%C3%A9sum%C3%A9%20M%C3%A4rz.txt
  Content-Type: text/plain
  Content-Length: 6
  Accept-Ranges: bytes
  Content-Range: bytes 10-15/36
  body: abcdef
GET /reports/latest, Range: bytes=-6 -> 206
  Content-Disposition: attachment; filename="Resume Maerz.txt"; filename*=UTF-8''R%C3%A9sum%C3%A9%20M%C3%A4rz.txt
  Content-Type: text/plain
  Content-Length: 6
  Accept-Ranges: bytes
  Content-Range: bytes 30-35/36
  body: uvwxyz
  • ContentDisposition.attachment().filename(name, UTF_8) wrote the name twice. filename*=UTF-8''R%C3%A9sum%C3%A9... is the RFC 6266 form that modern browsers use. filename="Resume Maerz.txt" is an ASCII fallback for older clients, with the accents replaced, which Spring added automatically.
  • attachment makes the browser save the file instead of displaying it. Use ContentDisposition.inline() to display it, for example a PDF in a browser tab.
  • Because the body is a Resource, Spring answered Range: bytes=10-15 with 206 Partial Content, the six bytes abcdef and Content-Range: bytes 10-15/36. The controller did nothing for this.
  • bytes=-6 asked for the last six bytes. Spring worked out that they are bytes 30 to 35 and returned uvwxyz.
  • Every response carried Accept-Ranges: bytes, which tells clients that they may resume an interrupted download.

For a file on disk, return a FileSystemResource or a PathResource; Spring streams it and sets the length. Never build the path from a request parameter without the same checks as for uploads, or the download endpoint becomes a way to read any file on the server.

Choosing an approach

Upload and download needs and what to use
NeedUse
One file from an HTML form@RequestParam MultipartFile
Several files in one fieldList<MultipartFile> or MultipartFile[]
Files with structured metadata@RequestPart with a JSON part, or text fields with @RequestParam
Large filestransferTo or getInputStream, never getBytes
Rejecting oversized uploads cleanlyLimits in properties, plus an @ExceptionHandler for MaxUploadSizeExceededException
A file name for storageOne you generate; keep the client's name only as data
Checking the file typeThe file's own bytes, not getContentType()
Downloads with non-ASCII namesContentDisposition with a charset
Resumable downloads and mediaReturn a Resource; ranges work automatically
Uploading from Java codeRestClient with MultipartBodyBuilder

For the controller basics used here, see Spring Boot @RestController, and for turning upload failures into consistent error responses, see Spring Boot exception handling.