Display pdf file from local disk in Laravel 5?

后端 未结 3 1607
盖世英雄少女心
盖世英雄少女心 2021-01-06 07:02

I have a Laravel 5.5 app where users with administrator privileges can upload files. After they upload the files I\'d like them to be able to view the file in the administra

相关标签:
3条回答
  • 2021-01-06 07:20

    If you want your files to be protected (only admin can access them), then you need to create a new route and new DocumentController method getDocument

    Add new route

    Route::get('documents/pdf-document/{id}', 'DocumentController@getDocument');
    

    In DocumentController, add

    use Storage;
    use Response;
    

    Add new method that will read your pdf file from the storage and return it back

    public function getDocument($id)
    {
        $document = Document::findOrFail($id);
    
        $filePath = $document->file_path;
    
        // file not found
        if( ! Storage::exists($filePath) ) {
          abort(404);
        }
    
        $pdfContent = Storage::get($filePath);
    
        // for pdf, it will be 'application/pdf'
        $type       = Storage::mimeType($filePath);
        $fileName   = Storage::name($filePath);
    
        return Response::make($pdfContent, 200, [
          'Content-Type'        => $type,
          'Content-Disposition' => 'inline; filename="'.$fileName.'"'
        ]);
    }
    

    In your view you can show the document like this

    <embed
        src="{{ action('DocumentController@getDocument', ['id'=> $document->id]) }}"
        style="width:600px; height:800px;"
        frameborder="0"
    >
    
    0 讨论(0)
  • 2021-01-06 07:23
    <embed
    src="{{ url('/filepath') }}"
    style="width:600px; height:800px;"
    frameborder="0">
    
    0 讨论(0)
  • 2021-01-06 07:42

    Shorter version of that Response::make() from @ljubadr answer:

    return Storage::response($document->file_path)

    0 讨论(0)
提交回复
热议问题