【问题标题】:How to serve the data returned from laravel Storage::disk('private')->get($file) as PDF如何将 laravel Storage::disk('private')->get($file) 返回的数据作为 PDF 提供
【发布时间】:2020-06-05 16:51:36
【问题描述】:

我的问题是关于以下链接中的问题:

Understanding file storage and protecting contents Laravel 5

我需要使用上面示例中提到的相同方法,但我需要提供 PDF 文件的下载链接或在浏览器中打开 PDF 文件的链接而不是图像,但我不能这样做,因为正如在以上示例的 cmets Storage::disk('private')->get($file) 返回文件的内容而不是 URL。

请告诉我如何将行数据(文件内容)转换为文件并为视图内的用户提供链接。

【问题讨论】:

  • 用户aceraven777回答了示例链接我希望他也回答这个问题:)
  • 当你点击链接 pdf 在浏览器新标签页中打开。

标签: laravel pdf blob laravel-filesystem


【解决方案1】:

您应该遵循以下步骤:

我已将 pdf 文件存储到 storage/app/pdf

在控制器中:

public function __construct()
{
    $this->middleware('auth');
}

public function index(Request $request, $file)
{   

    $file = storage_path('app/pdf/') . $file . '.pdf';

    if (file_exists($file)) {

        $headers = [
            'Content-Type' => 'application/pdf'
        ];

        return response()->file($file, $headers);
    } else {
        abort(404, 'File not found!');
    }        
}

如果 laravel 低于 5.2: 在控制器的控制器类上面添加use Response;。

public function index(Request $request, $file)
{   

    $file = storage_path('app/pdf/') . $file . '.pdf';

    return Response::make(file_get_contents($file), 200, [ 'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$file.'"'

    ]);       
}

在web.php

Route::get('/preview-pdf/{file}', 'Yourcontroller@index');

在刀片视图中:

<a href="{{ URL('/preview-pdf/'.$file )}}" target="_blank">PDf</a>

【讨论】:

  • 它不起作用,我试过但它返回一个空白页面,左上角有文件的url
  • @kianooshAzarvandi 能否在显示黑页时检查文件的 URL 是否正确?
  • 作为记录,我在一个单独的控制器中使用这个:$url = Storage::disk('private')-&gt;url($file);,该控制器负责创建到文件链接的路由
  • @kianooshAzarvandi 我已经在我的 laravel 项目中为你测试过,它正在工作。让我知道任何问题。
  • 您并没有将其设为私有,整个事情都是关于文件安全性,同时通过 Storage::disk('private') 仅向经过身份验证的用户提供文件,并在此处完成:stackoverflow.com/questions/57462558/…
【解决方案2】:

根据 Laravel documentation,您可以简单地在 Storage 门面上使用 download 方法。

从您的控制器返回命令的结果。

return Storage::disk('private')-&gt;download($file);

【讨论】:

  • 非常感谢您的帮助。它完全符合我的预期。
  • 还有一个问题,如何在浏览器中打开文件而不是下载文件?
  • @kianooshAzarvandi 您需要获取 URL,然后将此 URL 添加到目标为 blank 的锚标记中。我已经更新了我的答案。
  • @kianooshAzarvandi 我不完全确定 Laravel 5.1 是否支持文件响应,但你可以尝试return response()-&gt;file($pathToFile)。如果这不起作用,请尝试return response()-&gt;download($pathToFile, $name, ['Content-Type' =&gt; 'application/pdf', 'Content-Disposition' =&gt; "inline; filename=\"{$name}\""]); 您在这里所做的是修改 Content-Disposition 标头,以便浏览器显示文件而不是尝试下载它。
  • 未定义变量:pathToFile
猜你喜欢
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 2018-10-27
  • 2021-09-30
  • 2016-07-12
相关资源
最近更新 更多