在 Laravel 5 中显示本地磁盘中的 pdf 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46898095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:51:37  来源:igfitidea点击:

Display pdf file from local disk in Laravel 5?

phplaravellaravel-5file-upload

提问by Connor Leech

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 administrator dashboard.

我有一个 Laravel 5.5 应用程序,具有管理员权限的用户可以上传文件。在他们上传文件后,我希望他们能够在管理员仪表板中查看文件。

I have a DocumentController.phpthat handles the file upload to the local disk:

我有一个DocumentController.php来处理文件上传到本地磁盘:

public function store(Request $request)
{
    // check to make sure user is an admin
    $request->user()->authorizeRoles('admin');

    // validate that the document is a pdf and 
    // that required fields are filled out
    $this->validate($request, [
        'title' => 'required',
        'description' => 'required',
        'user_id' => 'required|exists:users,id', 
        'document_path' => 'required|mimes:pdf'
    ]);

    $file = $request->file('document_path');

    $path = $file->store('documents/' . $request->user_id);

    $document = Document::create([
        'user_id' => $request->user_id,
        'title' => $request->title,
        'description' => $request->description,
        'file_path' => $path
    ]);

    return redirect($document->path());
} 

This method takes the file from the form, makes sure it is a pdf and then saves the file to storage/app/documents/{user_id}. It then creates a Document record in the database and forwards to the URL based on the document id: /admin/document/{ $document->id }

此方法从表单中获取文件,确保它是 pdf,然后将文件保存到storage/app/documents/{user_id}。然后它在数据库中创建一个文档记录并根据文档 id 转发到 URL:/admin/document/{ $document->id }

That route is defined as Route::get('/admin/document/{document}', 'DocumentController@show');

该路线定义为 Route::get('/admin/document/{document}', 'DocumentController@show');

Where in the controller I pass the document to the view:

在控制器中,我将文档传递给视图:

public function show(Document $document, Request $request)
{
    // check to make sure user is an admin
    $request->user()->authorizeRoles('admin');

    $storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();

    return view('admin.document', compact('document', 'storagePath'));
}

On that page I would like to display the pdf document.

在该页面上,我想显示 pdf 文档。

resources/views/admin/document.blade.php

资源/视图/管理/document.blade.php

@extends('layouts.app')

@section('content')
<div class='container'>
    <div class='row'>
        <div class='col-sm-2'>
            <a href='/admin'>< Back to admin</a>
        </div>
        <div class='col-sm-8'>
            {{ $document }}

            <embed src="{{ Storage::url($document->file_path) }}" style="width:600px; height:800px;" frameborder="0">

        </div>
    </div>
</div>
@endsection

I have tried using the $storagePathvariable and Storagemethods but cannot get the pdf file to display within the iframe.

我尝试使用$storagePath变量和Storage方法,但无法让 pdf 文件显示在 iframe 中。

Using local file storage how would I display the file in the browser? Also, I've protected the route so that only admins can view the document's page but what is the best way to secure the path to the document itself?

使用本地文件存储如何在浏览器中显示文件?另外,我已经保护了路由,以便只有管理员才能查看文档页面,但是保护文档本身路径的最佳方法是什么?

回答by ljubadr

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

如果您希望您的文件受到保护(只有管理员可以访问它们),那么您需要创建一个新路由和新DocumentController方法getDocument

Add new route

添加新路线

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

In DocumentController, add

DocumentController 中,添加

use Storage;
use Response;

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

添加新方法,该方法将从存储中读取您的 pdf 文件并将其返回

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"
>

回答by jovani

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

Response::make()来自@ljubadr 的简短版本回答:

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

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

回答by saranya

<embed
src="{{ url('/filepath') }}"
style="width:600px; height:800px;"
frameborder="0">