Laravel 5.2 stream download

十年热恋 提交于 2019-12-24 06:38:46

问题


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.

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);

}

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

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?


回答1:


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);

I believe this uses the StreamedResponse class.



来源:https://stackoverflow.com/questions/37744260/laravel-5-2-stream-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!