概要
ファイルアップロードなどで動的にファイルをLaravelのプロジェクトに上げる方法は色んな所で紹介がありますが、単にprivateなファイルをプロジェクト内に入れてログインユーザーなどの特定の条件の人にだけ返すというのはあまり見かけなかったので書きます。
ファイルを置く
resources以下にファイルを置きます。正直public以外だったらどこに置いてもいい説ありますが、resourcesが名前的にもちょうど良さそうです。
|
+-- resources
+-- static
+-- hogehoge.pdf
ファイルを返す
file_get_contentsでファイルの中身を取り出してレスポンスにして返します。
DownloadController.php
<?php
use Illuminate\Contracts\Routing\ResponseFactory;
class DownloadController extends Controller {
public function __construct(
ResponseFactory $responseFactory
) {
$this->responseFactory = $responseFactory;
}
public function download()
{
$fileName = 'hogehoge.pdf';
$fileData = file_get_contents(resource_path('static/' . $fileName), FILE_USE_INCLUDE_PATH);
return $this->responseFactory->make(
$fileData,
200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename*=UTF-8\'\'' . rawurlencode($fileName)
]
);
}
}
以上です。