我有一个 Laravel 5.5 应用程序,具有管理员权限的用户可以在其中上传文件。在他们上传文件后,我希望他们能够在管理员仪表板中查看文件。
我有一个 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());
}
此方法从表单中获取文件,确保它是 pdf,然后将文件保存到 storage/app/documents/{user_id}。然后它在数据库中创建一个文档记录并转发到基于文档 ID 的 URL:/admin/document/{ $document->id }
该路由定义为 Route::get('/admin/document/{document}', 'DocumentController@show');
我在 Controller 中将文档传递给 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'));
}
在该页面上我想显示 pdf 文档。
resources/views/admin/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
我已尝试使用 $storagePath
变量和 Storage
方法,但无法让 pdf 文件显示在 iframe 中。
使用本地文件存储如何在浏览器中显示文件?此外,我已经保护了路由,以便只有管理员可以查看文档的页面,但是保护文档本身路径的最佳方法是什么?
最佳答案
如果您希望您的文件受到保护(只有管理员可以访问它们),那么您需要创建一个新路由和新的 DocumentController
方法 getDocument
添加新路线
Route::get('documents/pdf-document/{id}', 'DocumentController@getDocument');
在DocumentController中,添加
use Storage;
use Response;
添加从存储中读取您的 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.'"'
]);
}
在您的 View 中,您可以像这样显示文档
<embed
src="{{ action('DocumentController@getDocument', ['id'=> $document->id]) }}"
style="width:600px; height:800px;"
frameborder="0"
>
关于php - 在 Laravel 5 中显示本地磁盘中的 pdf 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46898095/