第一步:
// 封装 下载
function exportExcel(data, name) { if (!data) { return } const url = window.URL.createObjectURL(new Blob([data])) const link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', name) document.body.appendChild(link) link.click() window.URL.revokeObjectURL(url)}
第二步:(有些场景会需要)
将后台返回的url 再次调用 后台返回图片、文件的字节流数据。
第三步:将返回的字节流数据和文件名传入即可,一般返回的字节流数据是url格式的
exportExcel(url, fileName)
axios封装下载文档
function formateExcl(url, methods, data = {}, title) { axios({ method: methods, url, // 请求地址 params: data, data, // 参数 responseType: 'blob' // 表明返回服务器返回的数据类型 这里注意要加上responseType }) .then(res => { // 处理返回的文件流 // 注意 返回的res 无需做任何处理,有时在用框架封装的请求之后会出现返回response.text() 等情况导致文件流下载失败。 const content = res const blob = new Blob([content]) const fileName = title + '.xls' const alink = document.createElement('a') alink.download = fileName alink.style.display = 'none' alink.href = URL.createObjectURL(blob) // 这里是将文件流转化为一个文件地址 document.body.appendChild(alink) alink.click() URL.revokeObjectURL(alink.href) // 释放URL 对象 document.body.removeChild(alink) }) .catch(error => { console.log(error) // this.$message.error(error) })}