概要
Laravelを使って、ファイル名を指定してダウンロードを促すレスポンスを返します。
Content-Disposition
HTTPレスポンスのレスポンスヘッダーにContent-Dispositionを指定することによって、それがダウンロードすべきファイルである、名前は〇〇である、ということをブラウザに教えてあげることができます。
これをLaravelで実装します。
実装
DocumentController.php
<?php
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Contracts\Routing\ResponseFactory;
class DocumentController {
private $fileSystem;
private $responseFactory;
public function __construct(FilesystemAdapter $fileSystem, ResponseFactory $responseFactory)
{
$this->fileSystem = $fileSystem;
$this->responseFactory = $responseFactory;
}
... 略 ...
public function download($file) {
$data = $this->fileSystem->get($file); // S3などからファイルのrawDataを取ってくる
return $this->responseFactory->make($fileData->rawData, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . 'ファイル名' . '"'
]);
}
}
Content-Dispositionの値として attachment
を指定することによりダウンロードすべきであるということを教えます。その後ろに;
で区切ってfilename
を指定することによってファイル名を指定できます。