1、前端发起请求时的配置
{
url: url,
method: 'get',
params: data
responseType: 'blob',//很重要
}
例:返回的数据格式如下
Blob {size: 1054049, type: 'application/octet-stream'}
2、数据成功返回后,对数据进行处理
async downloadHandle(data) {
const result = await downloadBootLogo({ id: data });
const blob = new Blob([result], { type: result.type });
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob);
downloadElement.href = href;
const filename = new Date().getTime();//获取当前时间戳
downloadElement.download = filename;//给下载文件命名,避免重复
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement); //移除元素;防止连续点击创建多个a标签
window.URL.revokeObjectURL(href);
},
问题1、下载文件格式为csv时,用excel打开中文乱码
网上查看了很多,自己用给的代码案例发现都没有用。最后做了如下修改发现可以
const blob = new Blob(["\uFEFF", result], {
type: "data:text/csv; charset=utf-8,",
});