在调用中添加
responseType: "arraybuffer", //设置请求的方式,后台返回数据流,就要设置 arraybuffer 。
download2(params).then(ret => {//ret为后端文件
if (ret) {
let blob = new Blob([ret],
// { type: "application/vnd.ms-excel" }
);
let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob);
let downFile = document.createElement("a");
let fileName = "2.0下载.xls";
downFile.style.display = "none";
downFile.href = objectUrl;
downFile.download = fileName; // 下载后文件名
document.body.appendChild(downFile);
downFile.click();
document.body.removeChild(downFile); // 下载完成移除元素
window.URL.revokeObjectURL(objectUrl); // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。
}
})
本文介绍了一种使用JavaScript实现的文件下载方法。该方法通过设置响应类型为arraybuffer接收后台返回的数据流,并利用Blob对象创建文件下载链接。此外,还详细展示了如何设置下载文件名及确保Blob对象正确回收。
2828

被折叠的 条评论
为什么被折叠?



