如何直接从浏览器访问存储中的pdf文件?

时间:2017-09-01 14:39:31

标签: laravel laravel-5.2

我想从浏览器访问pdf文件,该文件位于laravel storage文件夹中。我不希望存储公开。

我不想下载它(我设法做到了)。我只想拥有一条获取路线,并在浏览器中显示该文件,如:www.test.com/admin/showPDF/123/123_321.pdf。

123是一个id。

如果我使用:

storage_path('app/'.$type.'/'.$fileName);
or
Storage::url('app/'.$type.'/'.$fileName);

返回完整的服务器路径。

感谢。

5 个答案:

答案 0 :(得分:0)

您可以从存储文件夹中读取它,然后将内容流式传输到浏览器并强制浏览器下载它。

$path = storage_path('app/'.$type.'/'.$fileName)

return Response::make(file_get_contents($path), 200, [
    'Content-Type' => 'application/pdf', //Change according to the your file type
    'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);

答案 1 :(得分:0)

您可以在存储/应用/公共和公共/存储之间建立符号链接,以便您可以通过运行

来访问您的文件
php artisan storage:link

更多信息Here

然后你可以制作这样的路线来访问文件:

Route::get('pdffolder/{filename}', function ($filename)
{
    $path = storage_path('app/public/pdffolder/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

因此,在这种情况下,如果您将名为123.pdf的pdf保存在文件夹storage/app/public/pdffolder

you can access it by http://yourdomain.com/pdffolder/123.pdf

你必须稍微调整一下,但我认为这可以帮助你。

答案 2 :(得分:0)

快速而肮脏,但您要做的是使用您在控制器方法(或路由关闭,您的呼叫)的响应中抓取的路径。类似的东西:

public function sendPdf(Request $request)
{
    // do whatever you need to do here, then
    ...
    // send the file to the browser
    $path = storage_path('app/'.$type.'/'.$fileName);
    return response()->file($path);
}

有关详细信息,请参阅https://laravel.com/docs/5.4/responses#file-responses,但这就是我的方式

答案 3 :(得分:0)

您必须在请求中流式传输文件。在您的控制器中执行以下操作

use Symfony\Component\HttpFoundation\Response;

...

function showPdf(Request $request, $type, $fileName)
{
   $content = file_get_contents(storage_path('app/'.$type.'/'.$fileName));

   return Response($content, 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => "inline; filename=\"$fileName\""
        ]);
}

这将直接传输您的PDF

答案 4 :(得分:0)

添加新路线以获取pdf

Route::get('/admin/showPDF/{$type}/{$fileName}','PDFController@pdf');

并在您的控制器中

public function pdf($type,$fileName)
    {
        $path = storage_path('app/'.$type.'/'.$fileName);
        return response()->file($path);
    }