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

我有一个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}.然后它在数据库中创建一个Document记录,并根据文档ID转发到URL:/ admin / document / {$document-> id}

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

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

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文档.

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

@extends('layouts.app')

@section('content')

{{ $document }}

@endsection

我尝试过使用$storagePath变量和存储方法,但无法在iframe中显示pdf文件.

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

解决方法:

如果您希望保护您的文件(只有管理员可以访问它们),那么您需要创建一个新的路由和新的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.'"'

]);

}

在您的视图中,您可以显示这样的文档

src="{{ action('DocumentController@getDocument', ['id'=> $document->id]) }}"

style="width:600px; height:800px;"

frameborder="0"

>

标签:php,file-upload,laravel,laravel-5

来源: https://codeday.me/bug/20190527/1163103.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值