ダウンロード

(spring_core_dart の) Resource を返すコントローラーメソッドは、その内容をレスポンスボディとして送ります。スターターはコンテンツタイプ、長さ、Accept-Ranges を設定し、ディスクからファイルをストリーミングし、Range、If-Modified-Since、HEAD のリクエストに自分で応答します。

使う理由

ファイルを提供するのは簡単そうに見えますが、良い応答には多くの細部があります。正しい Content-Type、Content-Length、ブラウザーの「名前を付けて保存」のためのファイル名、Range による再開可能なダウンロードと動画のシーク、そしてブラウザーが同じファイルを二度ダウンロードしないための 304 Not Modified です。Resource の戻り値はそのすべてを行います。あなたのメソッドが決めるのは、どのファイルか、そして ResponseEntity を使うならどの追加ヘッダーかだけです。

サイトがそのまま提供するファイル (Flutter Web のビルド、画像、CSS) にはコントローラーは不要です。静的リソース を参照してください。ファイルがリクエストに依存するときにコントローラーを使います。ログイン中のユーザーの請求書、生成したレポート、データベースで探したファイルなどです。

例

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;

  // ディスクの表紙画像をストリーミングする。パターンにより、ファイル名には
  // 数字しか入らない。パス変数はデコード済みなので、決してそのまま
  // パスに入れないこと。
  @GetMapping(r'/books/{isbn:\d+}/cover')
  Resource cover(@PathVariable() String isbn) =>
      FileSystemResource('/var/shop/covers/$isbn.png');

  // ブラウザーが 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()));

  // バージョンタグ付きの請求書: このバージョンを持っているブラウザーは
  // ボディなしの 304 を受け取る。
  @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'));
}

クライアントが受け取るもの:

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

応答に含まれるもの

ヘッダー 値
Content-Type ResponseEntity が設定しない限り、ファイル名の拡張子から (MediaTypeFactory、後述の表)。拡張子が不明な場合やファイル名がない場合 (ByteArrayResource) は application/octet-stream。
Content-Length 内容、または範囲のサイズ。
Accept-Ranges bytes: クライアントは範囲を要求できる。
Last-Modified ファイルの更新時刻。FileSystemResource の場合のみ。
Content-Range 206 と 416 の場合。
その他 ResponseEntity のヘッダー: Content-Disposition、Cache-Control、ETag など。

ルール:

コンテンツタイプ

タイプは拡張子から、大文字小文字を区別せずに決まります。

拡張子 タイプ
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') で同じ答えが得られます (不明なら null)。

別のタイプにするには、ResponseEntity で設定します: .contentType('application/epub+zip')。

server.mime-mappings.* はタイプを追加または変更しますが、それは 静的リソースだけ で、コントローラーが返す Resource には適用されません。

server:
  mime-mappings:
    wasm: application/wasm
    epub: application/epub+zip
キー 型 デフォルト 意味
server.mime-mappings.<extension> Map<String, String> 空 その拡張子を持つファイルのメディアタイプ。組み込みのものに追加される。ここに挙げた拡張子が優先される。拡張子は大文字小文字を区別せず、先頭のドットの有無も問わずに照合される。

ファイル名: Content-Disposition

Content-Disposition は、ボディをどう扱うか、どの名前を提示するかをブラウザーに伝えます。

(spring_web_dart の) ContentDisposition は、ヘッダーの値を正しく書きます。

コンストラクター ヘッダーの値
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

範囲

クライアントは Range で内容の一部を要求します。ダウンロードマネージャーの再開や、動画プレイヤーのシークです。

Range ヘッダー 応答
bytes=0-99 206、0 から 99 バイト目、Content-Range: bytes 0-99/<length>
bytes=500- 206、500 バイト目から最後まで
bytes=-100 206、最後の 100 バイト
10 バイトに対して bytes=5-100 206、5 から 9 バイト目 (終端は内容に合わせて切られる)
10 バイトに対して bytes=20-30 416 Range Not Satisfiable、Content-Range: bytes */10、ボディなし
bytes=0-1,4-5 (複数の範囲) 200、内容全体
items=0-1、bytes=-+3、bytes=0x1-0x2 (不正な形式) 200、内容全体

キャッシュ: ETag、Last-Modified、304

二つのチェックが、繰り返された GET や HEAD に、ボディなしの 304 Not Modified で応答します。

  1. ResponseEntity 自身の ETag と Last-Modified (.eTag(...) と .lastModified(...) で設定)。GET または HEAD に対する 200 の場合に、Spring の HttpEntityMethodProcessor と同じようにチェックされます。
    • タグを持つ If-None-Match (弱い比較。リストや複数のヘッダーも可): 304。* は GET には一致しません。
    • If-None-Match がなく、If-Modified-Since が Last-Modified 以降: 304。
    • If-Unmodified-Since が Last-Modified より前: 412 Precondition Failed。
  2. ファイル自身の更新時刻 (FileSystemResource): Last-Modified が設定され、それ以降の If-Modified-Since を持つ GET や HEAD は 304 を受け取ります。

304 は、本来そうあるべきとおり、他のヘッダー (Cache-Control、Vary、CORS のヘッダー) を保ちます。

Cache-Control は、ブラウザーやプロキシが問い合わせずに応答を保持できる時間を示します。CacheControl で組み立てます。

// 表紙はめったに変わらない: どのキャッシュでも 1 日保持し、その後に問い合わせる。
@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 ディレクティブ
CacheControl.maxAge(d) max-age=<seconds>
CacheControl.noCache() no-cache: サーバーに問い合わせた後でだけ再利用する
CacheControl.noStore() no-store: 決して保存しない
CacheControl.empty() まだディレクティブなし
.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 ヘッダーのテキスト。ディレクティブが設定されていなければ null

自分で応答を書くハンドラーも同じチェックを実行できます。ResponseWriter Bean の checkNotModified(request, response) は、リクエストの条件を、レスポンスにすでにある ETag と Last-Modified と比較します。

安全なファイル名

サーバーは、どのハンドラーよりも前に、パス中のエンコードされた /、\、NUL と、. や .. のセグメントを拒否します。それでもパス変数には、ファイル名が持つべきでない文字が含まれることがあります。パターンで制限する ({isbn:\d+}、{name:[a-z0-9-]+}) か、リクエストからパスを組み立てる代わりに、あなたのデータの中で ID によってファイルを探してください。MockMvc はサーバーのチェックを適用しないので、パターン自体をテストしてください。

テスト

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));

テスト を参照してください。

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)));
}

重要な違い:

関連項目