我正在尝试从服务器流式传输大型 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();}现在在前端,在控制台中,我可以看到按照需要的方式打印响应。然而,根据我的理解,后端应该触发要下载的文件,而这并没有发生。我在这里遗漏了什么,如何将其作为物理文件下载到前端?
1 回答
智慧大石
TA贡献1946条经验 获得超3个赞
如果您直接访问了 URL,您的 PHP 设置应该可以强制下载。但是你已经在一个完全加载的 HTML 页面中,所以你需要使用这个<iframe>技巧来下载文件。这将允许浏览器接收传入的数据,就像您打开了一个新的浏览器窗口一样。
尝试将您的下载功能更改为:
downloadCSVData() {
$('<iframe />')
.attr('src', '/downloadCSVData')
.hide()
.appendTo('body');
}
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报
0/150
提交
取消