2
1

More than 3 years have passed since last update.

Laravelで名前を指定してファイルをダウンロードできるようにする

Posted at

概要

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を指定することによってファイル名を指定できます。

2
1
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
2
1