Laravel 5.2流下载 [英] Laravel 5.2 stream download

查看:389
本文介绍了Laravel 5.2流下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对CSV下载有些困惑.我很高兴将其保存到文件中并提供给用户链接,但是从这些.

I'm getting a bit muddled with a CSV download. I'm very happy to save it to a file and supply a link to the user, but this seems like the wrong way to go judging from things like these.

从此答案开始使用Laravel将表下载为CSV 我想我已经发现stream()方法不再存在.

Going from this answer Use Laravel to Download table as CSV I think I've found that the stream() method no longer exists.

public function download()
{
    $headers = [
            'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0'
        ,   'Content-type'        => 'text/csv'
        ,   'Content-Disposition' => 'attachment; filename=galleries.csv'
        ,   'Expires'             => '0'
        ,   'Pragma'              => 'public'
    ];

    $list = $this->users->getAllUsers()->toArray();

    # add headers for each column in the CSV download
    array_unshift($list, array_keys($list[0]));

   $callback = function() use ($list) 
    {
        $FH = fopen('php://output', 'w');
        foreach ($list as $row) { 
            fputcsv($FH, $row);
        }
        fclose($FH);
    };

    // return Response::stream($callback, 200, $headers); // Old version
    return response()->download($callback, 'Users-' . date('d-m-Y'), $headers);

}

我尝试使用Laravel 5.2 response()函数,但是我对响应的内容有些困惑– download()似乎是合理的选择,但这给了我以下错误:

I've tried to use the Laravel 5.2 response() function, however I'm just getting a bit lost as to what I'm responding with – download() seems the logical option, but that gives me the following error:

关闭类的对象无法转换为字符串

Object of class Closure could not be converted to string

这有道理.解决这个问题的正确方法是什么?还是我应该保存文件,然后仅将文件路径用作我的download()函数的第一个参数-似乎有些不习惯?

Which makes sense. What is the right way of going about this? Or should I save the file and then just use the filepath as the first argument of my download() function – something that seems to be bad practise?

推荐答案

一旦我替换了&静态调用Response::使用辅助功能response()->:

It was simple enough and worked great once I replaced the class & static call Response:: With the helper function, response()->:

return response()->stream($callback, 200, $headers);

我相信它使用StreamedResponse类.

这篇关于Laravel 5.2流下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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