js把文件流导出下载excel文件

let btn = document.querySelector('#app > button');
let resData = null;
fetch('http://127.0.0.1:3333', {
method: "GET",
responseType: "blob"
})
.then(response => {
return response.blob()
})
.then(res => {
console.log(res);
resData = res;
})
btn.addEventListener("click", () => {
const link = document.createElement("a");
let blob = new Blob([resData], {
type: "application/octet-stream"
});
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.download = "xxxfile.xlsx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(link);
})

注意:需要设置 responseType: "blob" ,否则可能会出现下载的文件打开损坏问题。

动态截取请求中 content-disposition 的文件名:动态截取请求中 content-disposition 的文件名:

let fileName = res.headers["content-disposition"]
.split(";")[1]
.split("filename=")[1];
...
link.download = decodeURIComponent(fileName);

使用 decodeURIComponent 可以解决文件名乱码问题。

posted @   Li_pk  阅读(1616)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示