我正在生成一个CSV,我希望Laravel强制下载,但是文档只提到我可以下载已经存在于服务器上的文件,我想这样做而不将数据保存为文件.
我设法做了这个(有效),但我想知道是否有另一种更整洁的方式.
$headers = [
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="download.csv"',
];
return \Response::make($content, 200, $headers);
Run Code Online (Sandbox Code Playgroud)
我也尝试使用SplTempFileObject(),但是我收到以下错误:The file "php://temp" does not exist
$tmpFile = new \SplTempFileObject();
$tmpFile->fwrite($content);
return response()->download($tmpFile);
Run Code Online (Sandbox Code Playgroud)
Bri*_*ham 35
为更清晰的内容处理/ 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);
});
Run Code Online (Sandbox Code Playgroud)
然后在您的控制器或路线中,您可以返回以下内容
return response()->attachment($content);
Run Code Online (Sandbox Code Playgroud)
oma*_*ari 18
Laravel 7 方法将是(来自文档):
$contents = 'Get the contents from somewhere';
$filename = 'test.txt';
return response()->streamDownload(function () use ($contents) {
echo $contents;
}, $filename);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9633 次 |
| 最近记录: |