我正在尝试从服务器流式传输大型 CSV。我加载一个 JSON 文件,将其转换为数组,然后将其作为 CSV 进行处理。从前端,我通过单击按钮调用以下内容
downloadCSVData() {
axios({
url: '/downloadCSVData',
method: 'GET'
}).then((response) => {
console.log(response)
});
}
然后这个函数执行以下操作
public function downloadCSVData()
{
//load JSON file
$data = file_get_contents($file_path, true);
//Convert file to array
$array = json_decode($data, true);
$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'
];
$response = new StreamedResponse(function() use($array){
// Open output stream
$handle = fopen('php://output', 'w');
// Add CSV headers
fputcsv($handle, array_keys($array['element'][0]), ',');
foreach ($array['element'] as $key => $row) {
fputcsv($handle, $row);
}
// Close the output stream
fclose($handle);
}, 200, $headers);
return $response->send();
}
现在在前端,在控制台中,我可以看到按照需要的方式打印响应。然而,根据我的理解,后端应该触发要下载的文件,而这并没有发生。
我在这里遗漏了什么,如何将其作为物理文件下载到前端?
智慧大石