使用Laravel 9通过axios生成并下载csv文件

mpbci0fu  于 2023-04-27  发布在  iOS
关注(0)|答案(1)|浏览(109)

我正在使用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.

oyxsuwqo

oyxsuwqo1#

在Axios上试试这个

axios.post('{{ route("shiple.table") }}', filters, {responseType: 'arraybuffer'}) # changed
    .then(function (response) {
        const data = new Uint8Array(response.data); # changed
        const blob = new Blob([data], {type: 'text/csv;charset=utf-8;'}); # changed
        const url = window.URL.createObjectURL(blob);
        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);
    });

编辑01

axios.post('{{ route("shiple.table") }}', filters, {
    responseType: 'blob',
    headers: {
        'Accept': 'text/csv;charset=utf-8;', 
        'Content-Type': 'application/json'
    }
})
.then(function (response) {
    const url = window.URL.createObjectURL(new Blob([response.data], { type: 'text/csv;charset=utf-8;' }));
    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);
});

相关问题