问题
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