let blob = new Blob([res], { type: `application/vnd.openxmlformats-officedocument.spreadsheetml.shee` });//res就是后端接口返回的文件流;type是文件类型
let href = window.URL.createObjectURL(blob);
let downloadElement = document.createElement('a');
downloadElement.href = href;
// 下载后文件名
downloadElement.download = 'xxx名字.xlsx';
document.body.appendChild(downloadElement);
// 点击下载
downloadElement.click();
// 下载完成移除元素
document.body.removeChild(downloadElement);
// 释放掉blob对象
window.URL.revokeObjectURL(href);
*若下载还是乱码,在请求接口的请求头中加入 responseType: "blob"
例如
export function xxx(url, data, params, headers) {
return new Promise((resolve, reject) => {
axios({
method: 'POST',
url: url,
data: data,
params: params,
headers: headers,
responseType: "blob"//重点在此
}).then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}