LoginSignup
2
1

More than 3 years have passed since last update.

LaravelでプロジェクトにPrivateな静的ファイルを置く

Posted at

概要

ファイルアップロードなどで動的にファイルを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)
            ]
        );
    }
}

以上です。

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