はじめに
こんばんは。
あんまりダウンロード機能とか作ってなかったのですが、久々にLaravelで作ったので備忘録っときます。
めちゃ短いですが...
本題
<?php namespace App\Http\Controllers; use App\Model\File; use Illuminate\Http\Response; use Illuminate\Routing\ResponseFactory; class DownloadAction { public function __construct(private readonly ResponseFactory $responseFactory) { } public function __invoke(string $id): Response { $binary = Storage::get("{$id}"); return $this->responseFactory->make( $binary, 200, [ 'Content-Type' => 'octet-stream', 'Content-Disposition' => 'attachment; filename="ダウンロードファイル"', 'Content-Length' => strlen($binary) ] ); } }
ResponseFactoryのmakeで ヘッダーを生成してダウンロードできます。
終わりに
昔ながらの header関数
とかは使わなくてもいいって素敵ですね。
現場からは以上です。