Display pdf file from local disk in Laravel 5?

后端 未结 3 1633
盖世英雄少女心
盖世英雄少女心 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条回答
  •  猫巷女王i
    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

    
    

提交回复
热议问题