1、写在项目目录utils中,当作一个公共方法-在需要的地方去引用这个方法
const downloadFile = (res:any,name:string,str:string='pdf')=>{
let u8Arr = new Uint8Array(res);
let blob = new Blob([u8Arr], { type: "application/octet-binary" });
// 下载文件
let url = window.URL.createObjectURL(blob);
// 创建a标签,并隐藏改a标签
let link = document.createElement('a')
link.style.display = 'none'
// a标签的href属性指定下载链接
link.href = url
//setAttribute() 方法添加指定的属性,并为其赋指定的值。
const date = new Date()
let fileName = `${name}_${date.getFullYear()}_${(date.getMonth() + 1+'').padStart(2,'0')}_${(date.getDate()+'').padStart(2,'0')}_${(date.getHours()+'').padStart(2,'0')}_${(date.getMinutes()+'').padStart(2,'0')}_${(date.getSeconds()+'').padStart(2,'0')}` + "."+str;
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click();
}
export default downloadFile
2、在需要的页面引用
import downloadFile from "@/utils/downloadFile"
const exportFile = async ()=>{
const {data} = await request.get('/api/ExportUserFile')
if (data.success) {
downloadFile(data.data, `xx表`, 'xlsx')
}else{
ElMessage.error(data.message)
}
}