在 Laravel 5.2 中流式传输 PDF 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40860891/
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
Stream a PDF file in Laravel 5.2
提问by Anna Jeanine
Hi everyone!I'm working on a Laravel 5.2 application in which the user can download a variety of files. One of these is a 'User guide', explaining how the website is set up and functionalities etc. I would like the PDF to be streamed in another page, so that the user is still within the application. The controller which I am using is:
嗨,大家好!我正在开发一个 Laravel 5.2 应用程序,用户可以在其中下载各种文件。其中之一是“用户指南”,解释了网站的设置方式和功能等。我希望将 PDF 流式传输到另一个页面中,以便用户仍在应用程序中。我使用的控制器是:
public function userguidePDF(){
return response()->stream('../public/download/userguide.pdf');
}
But this returns:
但这会返回:
Argument 1 passed to Symfony\Component\HttpFoundation\StreamedResponse::__construct() must be callable, string given, called in /path/to/laravel/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php on line 117 and defined
传递给 Symfony\Component\HttpFoundation\StreamedResponse::__construct() 的参数 1 必须是可调用的,给定的字符串,在第 117 行的 /path/to/laravel/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php 中调用并定义
I have searched on the internet for a method, which leaded me to the following syntax:
我在互联网上搜索了一种方法,导致我使用以下语法:
return response()->stream($callback, 200, $headers);
Unfortunately, I am unable to find more documentation on the parameters because I don't understand them. Could someone please explain to me what the $callback, 200, $header
are as parameters and how I can use this?
不幸的是,我无法找到有关参数的更多文档,因为我不了解它们。有人可以向我解释什么$callback, 200, $header
是参数以及我如何使用它吗?
采纳答案by Jari Pekkala
https://laravel.com/docs/5.2/responses#view-responses
https://laravel.com/docs/5.2/responses#view-responses
public function userguidePDF() {
return response()->file(
public_path('download/userguide.pdf')
);
}
回答by Sitethief
$callback should be a function that ouputs your PDF. For example:
$callback 应该是一个输出 PDF 的函数。例如:
$callback = function()
{
$handle = fopen("../public/download/userguide.pdf", "r");
$filecontent= fread($handle, filesize("../public/download/userguide.pdf"));
fclose($handle);
return $filecontent;
};
回答by Sreejith Sasidharan
You can use download also
您也可以使用下载
return Response::download($file, 'filename.pdf', $headers);
here is the documentation for streaming and also downlaod. https://laravel.com/api/5.2/Illuminate/Routing/ResponseFactory.html#method_stream
这是流媒体和下载的文档。 https://laravel.com/api/5.2/Illuminate/Routing/ResponseFactory.html#method_stream
EDIT
编辑
Use headers like this
使用这样的标题
// We'll be outputting a PDF
header('Content-Type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');