前端vue导出后端返回的word excel zip流文件下载
在日常开发中,我们可能会遇到导出excel word的情况,而后端此时给我们返回的是一个文件流,需要前端将文件流转为url地址进行下载。 可以将这个方法封装成一个工具类,方便其他地方调用,我这里放到了utils.js里面
js:
export function exportFile(data,type, fileName) {
let blob = new Blob([data], {
//type类型后端返回来的数据中会有,根据自己实际进行修改
// 表格下载为 application/xlsx,压缩包为 application/zip等,
type: type
});
let filename = fileName;
if (typeof window.navigator.msSaveBlob !== "undefined") {
window.navigator.msSaveBlob(blob, filename);
} else {
var blobURL = window.URL.createObjectURL(blob);
// 创建隐藏<a>标签进行下载
var tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = blobURL;
tempLink.setAttribute("download", filename);
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);//移除dom元素
window.URL.revokeObjectURL(blobURL);//释放bolb内存
}
}
在vue中引用该方法
//导出文件方法
exportFile() {
let obj = {
dataid: this.companyInfo.dataId,
id: this.companyInfo.id,
template: this.radio,
year: this.companyInfo.year
}
exportWordForQuality(obj)
.then(res => {
console.log('质量审核-填报说明导出:', res.data);
const { data } = res
let fileName = `${this.companyObj.companyName}执行报告审核意见`
exportFile(data, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', fileName)
})
.catch(err => {
console.log(err);
})
},
注意:
(1)本方法中并没有设计压缩,如倒出的文件大,强烈建议使用jsZip
先安装在使用:import JSZip from 'jszip'
(2)exportWordForQuality ()接口中的响应格式要设置为bolb
//下载质量审核文件
export function exportWordForQuality(data) {
return req.post('/qualityAudit/report/exportWordForQuality', data, {
'responseType': 'blob'
})
}
(3)网页响应头content-type:
word文件:
.doc格式的content-type设置为:application/vnd.msword;charset=utf-8
.docx格式的content-type设置为:application/vnd.openxmlformats-officedocument.wordprocessingml.document
excel文件:
.xls格式的content-type设置为:application/vnd.ms-excel
.xlsx格式的content-type设置为:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
zip文件:
. zip格式的content-type设置为:application/zip
关于content-type设置格式参考:https://www.ibm.com/docs/en/wkc/cloud?topic=catalog-previews
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具