4
7

More than 1 year has passed since last update.

Laravel でのファイルダウンロードを実装してみた

Last updated at Posted at 2021-07-20

LaravelでPDFファイルのダウンロードを実装してみて、こんなに簡単に実装できるんだ、、、と驚いたので書いてみた

仕様、もしくは前提

・OS : Windows
・PHP 7.4.16 (cli) (built: Mar 2 2021 14:06:15) ( ZTS Visual C++ 2017 x64 )
・Laravel Framework 6.20.24
・ある画面に表示される「PDF出力」ボタンをクリックすると、DBに登録されているPDFファイルのパスを取得し、ブラウザ経由でローカルにPDFファイルがダウンロードされる。

1.PDFファイルのパス取得

$res = \DB->table('files')
       ->where('id', '=', $id)
       ->get();
$pdfFilePath = $res->pdf_pile_path;
//C:\LaravelDir\storage\app\public\pdfFiles\202107191038162092931173.pdf
$pdfFileName = pathinfo($pdfFilePath)['basename'];
//202107191038162092931173.pdf

2.ヘッダー情報指定

$headers = [
   'Content-Type' => 'application/pdf'
];

3.ファイルが存在したらダウンロード

if(file_exists($pdfFilePath)){
    return response()->download($pdfFilePath, $pdfFileName, $headers);
}else{
    //ファイルが存在しなかった場合のエラー処理
}

まとめ

こんな感じです。
他にもStorage::download()Storage::response()を使う方法があるみたいですが、今回は使いませんでした。

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7