Laravel - display a PDF file in storage without forcing download?

后端 未结 10 1044
陌清茗
陌清茗 2020-12-02 10:31

I have a PDF file stored in app/storage/, and I want authenticated users to be able to view this file. I know that I can make them download it using

return          


        
10条回答
  •  感情败类
    2020-12-02 11:02

    Update for 2017

    As of Laravel 5.2 documented under Other response types you can now use the file helper to display a file in the user's browser.

    return response()->file($pathToFile);
    
    return response()->file($pathToFile, $headers);
    

    Source/thanks to below answer

    Outdated answer from 2014

    You just need to send the contents of the file to the browser and tell it the content type rather than tell the browser to download it.

    $filename = 'test.pdf';
    $path = storage_path($filename);
    
    return Response::make(file_get_contents($path), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filename.'"'
    ]);
    

    If you use Response::download it automatically sets the Content-Disposition to attachment which causes the browser to download it. See this question for the differences between Content-Disposition inline and attachment.

    Edit: As per the request in the comments, I should point out that you'd need to use Response at the beginning of your file in order to use the Facade.

    use Response;
    

    Or the fully qualified namespace if Response isn't aliased to Illuminate's Response Facade.

提交回复
热议问题