使用Response :: download在laravel中下载文件 [英] Download files in laravel using Response::download
问题描述
在Laravel应用程序中,我试图在视图内部实现一个按钮,该按钮可以允许用户下载文件而无需导航至任何其他视图或路径 现在我有两个问题: (1)下面的函数抛出
In Laravel application I'm trying to achieve a button inside view that can allow user to download file without navigating to any other view or route Now I have two issues: (1) below function throwing
The file "/public/download/info.pdf" does not exist
(2)下载"按钮不应将用户导航到任何地方,而应仅在同一视图(我的当前设置)上下载文件,将视图路由到"/download"
(2) Download button should not navigate user to anywhere and rather just download files on a same view, My current settings, routing a view to '/download'
这是我要达到的目标:
按钮:
<a href="/download" class="btn btn-large pull-right"><i class="icon-download-alt"> </i> Download Brochure </a>
路线:
Route::get('/download', 'HomeController@getDownload');
控制器:
public function getDownload(){
//PDF file is stored under project/public/download/info.pdf
$file="./download/info.pdf";
return Response::download($file);
}
推荐答案
尝试一下.
public function getDownload()
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path(). "/download/info.pdf";
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, 'filename.pdf', $headers);
}
"./download/info.pdf"
将不起作用,因为您必须提供完整的物理路径.
"./download/info.pdf"
will not work as you have to give full physical path.
更新2016年5月20日
Laravel 5、5.1、5.2或5. *用户可以使用以下方法代替Response
facade.但是,我先前的答案对Laravel 4或5都适用.($header
数组结构更改为关联数组=>
-删除"Content-Type"后的冒号-如果我们不进行这些更改,则标头会以错误的方式添加:标头的名称应为从0,1,...开头的数字
Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of Response
facade. However, my previous answer will work for both Laravel 4 or 5. (the $header
array structure change to associative array =>
- the colon after 'Content-Type' was deleted - if we don't do those changes then headers will be added in wrong way: the name of header wil be number started from 0,1,...)
$headers = [
'Content-Type' => 'application/pdf',
];
return response()->download($file, 'filename.pdf', $headers);
这篇关于使用Response :: download在laravel中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!