首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将从laravel Storage::disk('private')->get($file)返回的数据作为PDF提供

如何将从laravel Storage::disk('private')->get($file)返回的数据作为PDF提供
EN

Stack Overflow用户
提问于 2020-02-21 17:25:19
回答 2查看 3.3K关注 0票数 2

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

Understanding file storage and protecting contents Laravel 5

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-21 17:32:59

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

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

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

票数 -1
EN

Stack Overflow用户

发布于 2020-02-21 17:33:43

您应该执行以下步骤:

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

在控制器中:

代码语言:javascript
复制
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;添加到控制器类之上。

代码语言:javascript
复制
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

代码语言:javascript
复制
Route::get('/preview-pdf/{file}', 'Yourcontroller@index');

在刀片视图中:

代码语言:javascript
复制
<a href="{{ URL('/preview-pdf/'.$file )}}" target="_blank">PDf</a>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60335586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档