Video in progress
How do you write a large file download endpoint in Spring?
Don't load the file into memory as a byte[]; stream it into the response: return a Resource (FileSystemResource) or use StreamingResponseBody. Set Content-Disposition and Content-Length in the headers.
📖 Answer
A common mistake:
byte[] data = Files.readAllBytes(path); // a 2 GB file = 2 GB of heap
return ResponseEntity.ok(data);
A few parallel downloads and the server dies with OOM.
The simple and correct version:
@GetMapping("/files/{id}")
public ResponseEntity<Resource> download(@PathVariable UUID id) throws IOException {
Path path = storage.pathOf(id);
Resource res = new FileSystemResource(path);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(Files.size(path))
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment().filename("report.pdf", StandardCharsets.UTF_8).build().toString())
.body(res);
}
Spring writes it in chunks with a buffer and also supports Range requests, which matters for video or resuming an interrupted download.
If the data isn't coming from a file but is being generated (say, a CSV from the DB), StreamingResponseBody is handy: the writing happens on a separate thread. In that case don't forget spring.mvc.async.request-timeout, otherwise a long export gets cut off halfway.
For Uzbek letters in the file name, the ContentDisposition builder adds filename*=UTF-8''... itself; if you build the string by hand, browsers mangle the name.
Sign up to mark studied questions and save your progress.