在项目中,后端要求下载时要进行后端的权限验证,发现a链接进行直接下载无法满足这个需求,只能通过blob对象来进行下载操作,翻阅大量资料最后实现该功能。以下是我个人的理解,如有不足,请各位大佬多指教
// 导出excel
export function exportFile2excel(fileName, url, params) { service.get(url, { params }).then((res) => { if(!res){ Message({ message: '暂无可下载数据', type: 'error', duration: 5 * 1000 }) }else{ //该部分为主要代码,与接口衔接即可,其余部分可以忽略 const blob = new Blob([res], { type: 'application/vnd.ms-excel' }); const urls = window.URL.createObjectURL(blob); const a = document.createElement('a');//生成虚拟a标签 a.href = urls; a.download = [fileName]; a.click(); window.URL.revokeObjectURL(urls); } }) }
在其它页面调用该方法即可
import { exportFile2excel } from '文件路径'
//导出招标文件购买记录
export function export(data) { const fileName = 'XXX一览表' const url = '接口路径' const sendData={ //传输的数据 projid: data.projid, bidid: data.bidid } return exportFile2excel(fileName, url, sendData ) }
在vue页面写个按钮调用该方法(export)即可
blob导出不同文件所需格式类型
文件后缀 | content-type |
---|---|
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.xls | application/vnd.ms-excel |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.ppt | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
前端新人,如有问题和不足之处,请指出,谢谢