Streaming downloads
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
send big files without loading them into memory.
Planned topics
- Reading a whole file into a
byte[]uses memory per request; ten parallel downloads can crash the server. - Return a
Resource(for exampleFileSystemResource) or aStreamingResponseBody; Spring copies it in chunks. - Set
Content-Typefrom your stored record, andContent-Lengthwhen known. Content-Disposition: attachment; filename="..."makes browsers download;inlinedisplays.- Return
404if the file record or file is missing.
Draft outline details
Demonstration
@GetMapping("/images/{id}")
ResponseEntity<Resource> download(@PathVariable String id) {
Resource r = storage.load(id);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(r);
}Check your understanding
Why not return a byte[]?
Show answer
The whole file sits in memory for each request.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.