Downloads
A controller method that returns a Resource (from spring_core_dart) sends its content as the response body. The starter sets the content type, the length and Accept-Ranges, streams files from disk, and answers Range, If-Modified-Since and HEAD requests by itself.
Why
Serving a file looks simple, but a good answer has many details: the right Content-Type, a Content-Length, a file name for the browser's "Save as", resumable downloads and video seeking with Range, and 304 Not Modified so a browser does not download the same file twice. A Resource result does all of it. Your method only decides which file, and with a ResponseEntity which extra headers.
For files that a site serves as they are (a Flutter web build, images, CSS), you do not need a controller: see Static resources. Use a controller when the file depends on the request: an invoice of the logged-in user, a generated report, a file looked up in a database.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
@Service()
class Reports {
String csv() => 'isbn,title\n9780441013593,Dune\n';
}
@RestController()
@RequestMapping('/api')
class DownloadController {
DownloadController(this.reports);
final Reports reports;
// A cover from disk, streamed. The pattern lets only digits into the
// file name: a path variable is decoded, so never put it into a path
// as it is.
@GetMapping(r'/books/{isbn:\d+}/cover')
Resource cover(@PathVariable() String isbn) =>
FileSystemResource('/var/shop/covers/$isbn.png');
// A generated report that the browser saves as report.csv.
@GetMapping('/report')
ResponseEntity<Resource> report() => ResponseEntity.status(HttpStatus.ok)
.contentType('text/csv; charset=utf-8')
.header(HttpHeaders.contentDispositionHeader, [
'${const ContentDisposition.attachment(filename: 'report.csv')}',
])
.header(HttpHeaders.cacheControlHeader, [
CacheControl.noStore().headerValue!,
])
.body<Resource>(ByteArrayResource.fromString(reports.csv()));
// An invoice with a version tag: a browser that has this version gets a
// 304 without a body.
@GetMapping(r'/invoices/{id:\d+}')
ResponseEntity<Resource> invoice(@PathVariable() String id) =>
ResponseEntity.status(HttpStatus.ok)
.eTag('"invoice-$id-v3"')
.header(HttpHeaders.contentDispositionHeader, [
'${ContentDisposition.inline(filename: 'invoice-$id.pdf')}',
])
.body<Resource>(FileSystemResource('/var/shop/invoices/$id.pdf'));
}
What a client gets:
GET /api/books/9780441013593/cover
200 OK
Content-Type: image/png
Content-Length: 48213
Accept-Ranges: bytes
Last-Modified: Tue, 03 Nov 2026 09:12:44 GMT
GET /api/books/9780441013593/cover Range: bytes=0-99
206 Partial Content
Content-Range: bytes 0-99/48213
Content-Length: 100
What the answer carries
| Header | Value |
|---|---|
Content-Type |
From the file name's extension (MediaTypeFactory, table below), unless the ResponseEntity sets one. application/octet-stream when the extension is unknown or there is no file name (a ByteArrayResource). |
Content-Length |
The size of the content, or of the range. |
Accept-Ranges |
bytes: the client may ask for ranges. |
Last-Modified |
The file's modification time, for a FileSystemResource only. |
Content-Range |
For a 206 and a 416. |
| Anything else | The headers of the ResponseEntity: Content-Disposition, Cache-Control, ETag, ... |
Rules:
- A
FileSystemResourceis streamed from disk, never read whole, also for a range (openRead(start, end)). - Any other
Resource(aByteArrayResource, an embeddedresources:file, aUrlResource) is read whole into memory, then sent. - A resource that does not exist or cannot be read is a
404problem (No resource cover.png). HEADgets the same status and headers without the body. EveryGETmapping answersHEADby itself.- The status of a
ResponseEntity<Resource>is kept.RangeandIf-Modified-Sinceare only looked at when it is200. - A
Resourcegets noETagby itself. Set one withResponseEntity...eTag(...)(see "Caching" below). The static resources have one.
Content types
The type comes from the extension, in any case:
| Extensions | Type |
|---|---|
txt, html/htm, css, csv, md |
text/plain, text/html, text/css, text/csv, text/markdown |
js, mjs |
text/javascript |
json, map |
application/json |
xml |
application/xml |
yaml, yml |
application/yaml |
webmanifest |
application/manifest+json |
wasm |
application/wasm |
pdf, zip, gz, tar |
application/pdf, application/zip, application/gzip, application/x-tar |
png, jpg/jpeg, gif, webp, avif, svg, ico, bmp |
image/png, image/jpeg, image/gif, image/webp, image/avif, image/svg+xml, image/vnd.microsoft.icon, image/bmp |
mp3, ogg, wav |
audio/mpeg, audio/ogg, audio/wav |
mp4, webm, mov |
video/mp4, video/webm, video/quicktime |
woff, woff2, ttf, otf |
font/woff, font/woff2, font/ttf, font/otf |
MediaTypeFactory.getMediaType('dune.png') gives the same answer in your own code (null when unknown).
For another type, set it on the ResponseEntity: .contentType('application/epub+zip').
server.mime-mappings.* adds or changes types for the static resources only, not for a Resource a controller returns:
server:
mime-mappings:
wasm: application/wasm
epub: application/epub+zip
| Key | Type | Default | Meaning |
|---|---|---|---|
server.mime-mappings.<extension> |
Map<String, String> |
empty | The media type of files with that extension, on top of the built-in ones. An extension listed here wins. The extension is matched in any case, with or without a leading dot. |
The file name: Content-Disposition
Content-Disposition tells the browser what to do with the body and which name to offer:
attachment: save it as a file;inline: show it (a PDF in the browser's viewer), with a name for when the user saves it.
ContentDisposition (from spring_web_dart) writes the header value correctly:
| Constructor | Header value |
|---|---|
ContentDisposition.attachment(filename: 'report.csv') |
attachment; filename="report.csv" |
ContentDisposition.inline(filename: 'invoice.pdf') |
inline; filename="invoice.pdf" |
ContentDisposition.attachment(filename: 'Bücher.csv') |
attachment; filename*=UTF-8''B%C3%BCcher.csv |
ContentDisposition('attachment') |
attachment |
- Quotes and backslashes in the name are escaped.
- A name that is not printable ASCII is written in the
filename*form of RFC 5987, which every browser reads. ContentDisposition.parse(value)reads such a header back.request.headers.contentDispositionandresponse.headers.contentDisposition = ...get and set it on headers.
Ranges
A client asks for part of the content with Range: a download manager resumes, a video player seeks.
Range header |
Answer |
|---|---|
bytes=0-99 |
206, bytes 0 to 99, Content-Range: bytes 0-99/<length> |
bytes=500- |
206, from byte 500 to the end |
bytes=-100 |
206, the last 100 bytes |
bytes=5-100 on 10 bytes |
206, bytes 5 to 9 (the end is cut to the content) |
bytes=20-30 on 10 bytes |
416 Range Not Satisfiable, Content-Range: bytes */10, no body |
bytes=0-1,4-5 (several ranges) |
200, the whole content |
items=0-1, bytes=-+3, bytes=0x1-0x2 (malformed) |
200, the whole content |
- One range per request. Several ranges get the whole content, not
multipart/byteranges. RFC 9110 allows a server to ignoreRange. - Positions are decimal digits only. Signs, other bases and numbers too large for an
intmake the header malformed. If-Rangewith a date: the range applies only when the file'sLast-Modifiedis that date (in whole seconds); otherwise the whole content is sent with200. This keeps a client from joining pieces of two versions.If-Rangewith an entity tag never matches a controller'sResource; the static resources compare it with theirETag.
Caching: ETag, Last-Modified and 304
Two checks answer a repeated GET or HEAD with 304 Not Modified and no body:
- The
ResponseEntity's ownETagandLast-Modified(set with.eTag(...)and.lastModified(...)), for a200to aGETorHEAD, as Spring'sHttpEntityMethodProcessorchecks them:If-None-Matchwith the tag (compared weakly, a list or several headers):304.*does not match aGET.- Without
If-None-Match,If-Modified-Sinceat or afterLast-Modified:304. If-Unmodified-SincebeforeLast-Modified:412 Precondition Failed.
- The file's own modification time (a
FileSystemResource):Last-Modifiedis set, and aGETorHEADwith anIf-Modified-Sinceat or after it gets304.
A 304 keeps the other headers (Cache-Control, Vary, CORS headers), as it should.
Cache-Control says how long a browser or proxy may keep the answer without asking. Build it with CacheControl:
// Covers change rarely: a day in any cache, then ask again.
@GetMapping(r'/books/{isbn:\d+}/thumbnail')
ResponseEntity<Resource> thumbnail(@PathVariable() String isbn) =>
ResponseEntity.status(HttpStatus.ok)
.header(HttpHeaders.cacheControlHeader, [
CacheControl.maxAge(const Duration(days: 1)).cachePublic().headerValue!,
])
.body<Resource>(FileSystemResource('/var/shop/thumbs/$isbn.webp'));
CacheControl |
Directive |
|---|---|
CacheControl.maxAge(d) |
max-age=<seconds> |
CacheControl.noCache() |
no-cache: reuse only after asking the server |
CacheControl.noStore() |
no-store: never store |
CacheControl.empty() |
no directive yet |
.mustRevalidate(), .noTransform(), .cachePublic(), .cachePrivate(), .proxyRevalidate() |
must-revalidate, no-transform, public, private, proxy-revalidate |
.sMaxAge(d), .staleIfError(d), .staleWhileRevalidate(d) |
s-maxage=, stale-if-error=, stale-while-revalidate= |
.immutable() |
immutable |
headerValue |
The text of the header, null when no directive is set |
A handler that writes its answer itself can run the same checks: the ResponseWriter bean's checkNotModified(request, response) compares the request's conditions with the ETag and Last-Modified already on the response.
Safe file names
The server refuses an encoded /, \ or NUL in a path and . or .. segments before any handler runs. A path variable can still hold characters a file name should not have. Restrict it with a pattern ({isbn:\d+}, {name:[a-z0-9-]+}), or look the file up by id in your own data instead of building a path from the request. MockMvc does not apply the server's checks, so test the pattern itself.
Testing
final result = await app.mockMvc
.get('/api/books/9780441013593/cover', headers: {'Range': 'bytes=0-99'})
.andExpect(status: 206, headers: {'Content-Range': 'bytes 0-99/48213'})
.andReturn();
expect(result.response.bodyBytes, hasLength(100));
See Testing.
In Spring (Java)
@GetMapping("/api/report")
ResponseEntity<Resource> report() {
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("text/csv"))
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment().filename("report.csv").build().toString())
.body(new ByteArrayResource(reports.csv().getBytes(UTF_8)));
}
Differences that matter:
- One byte range per request. Spring answers several ranges with
multipart/byteranges. ContentDispositionhas constructors instead of a builder.ResponseEntity.ok()without a body isResponseEntity.status(HttpStatus.ok)here.server.mime-mappingscovers the static resources only.
See also
- Uploads
- StreamingResponseBody: a body written on the fly
- Static resources
- Results
- @PathVariable
- Resource