原本的代码是,通过fetch请求拿到response对象,再通过response.blob()
转化为blob对象,再通过URL.createObjectURL
创建a标签的url来实现下载
部分代码如下
const response = await fetch(url, request);
const blob = await response.blob();
const link = document.createElement('a');
link.download= decodeURIComponent(filename);
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
以上代码下载下来的csv文件,如果包含中文,则中文部分会出现乱码
因此,更改部分代码,将拿到的response转化为text,即response.text()
,再在文件开头加上BOM头,\ufeff
,下载的文件中,中文就不会乱码啦
const text = await response.text();
const blob = new Blob([`\ufeff${text}`], { type: 'text/csv;charset=utf-8;' });
参考自:https://zhuanlan.zhihu.com/p/26434383