我正在生成CSV,我希望Laravel强制下载,但是the documentation只提到我可以下载服务器上已经存在的文件,我想这样做而不将数据保存为文件。
我设法做到了(这有效),但我想知道是否还有另一种更整洁的方式。
$headers = [
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="download.csv"',
];
return \Response::make($content, 200, $headers);
我也试过了SplTempFileObject(),但我收到了以下错误:The file "php://temp" does not exist
$tmpFile = new \SplTempFileObject();
$tmpFile->fwrite($content);
return response()->download($tmpFile);
答案 0 :(得分:32)
制作response macro以获得更清晰的内容处理/ laravel方法
将以下内容添加到App\Providers\AppServiceProvider
启动方法
\Response::macro('attachment', function ($content) {
$headers = [
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="download.csv"',
];
return \Response::make($content, 200, $headers);
});
然后在您的控制器或路线中,您可以返回以下内容
return response()->attachment($content);
答案 1 :(得分:9)
Laravel 7的方法是(来自docs):
cache
答案 2 :(得分:-3)
试试这个:
// Directory file csv, You can use "public_path()" if the file is in the public folder
$file= public_path(). "/download.csv";
$headers = ['Content-Type: text/csv'];
//L4
return Response::download($file, 'filename.csv', $headers);
//L5 or Higher
return response()->download($file, 'filename.csv', $headers);