我正在使用Laravel 9。从Axios,我调用一个路由,它生成一个数组的数组,以创建一个csv。我如何下载csv,而不必事先将其保存在服务器上?使用以下代码,我得到它来生成和下载它,正确的csv格式,它占用了大约14kb。但我无法用任何程序打开它(excel,vscode,notepad...),我想是因为编码问题吧?
在服务器上:
$full = array_merge($header,$lines);
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=file.csv",
"Pragma" => "no-cache",
"Content-Encoding" => "UTF-8",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$callback = function() use($full) {
$file = fopen('php://output', 'w');
//fputs($file, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) )); same result
fputcsv($file, $full);
fclose($file);
};
return response()->stream($callback, 200, $headers);
Axios呼吁客户:
axios.post('{{ route("shiple.table") }}', filters)
.then(function (response) {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.csv');
document.body.appendChild(link);
link.click();
})
.catch(function (error) {
console.log(error);
});
如果我用记事本打开它,它看起来很混乱:I don't know. I don't know.
1条答案
按热度按时间oyxsuwqo1#
在Axios上试试这个
编辑01