使用 Response::download 在 laravel 中下载文件 [英] Download files in laravel using Response::download

查看:46
本文介绍了使用 Response::download 在 laravel 中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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) 下载按钮不应将用户导航到任何地方,而应仅在同一视图中下载文件,我当前的设置,将视图路由到/下载"

(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'

这是我尝试实现的方式:

Here is how Im trying to achieve:

按钮:

  <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 门面.但是,我之前的答案适用于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆