Here we briefly record how Vue implements blob document streaming to download files, by calling the backend interface or returning a very messy data.
As shown below
Note: What needs special attention here is that regardless of whether the interface is a get or post request, an additional parameter needs to be added when requesting responseType:'blob' ,否则等等下载的文件会出现乱码
Common axios requests are as follows:
//post请求
axios.post(url, {...params}, {responseType: 'blob'}).then((res) => {
}).catch((err) => {
})
//get请求
axios.get(url, {params: {}, responseType: 'blob'}).then((res) => {
}).catch((err) => {
})
If it is encapsulated axios, add it when requesting.
The following is the operation after the interface is successfully called back.
//下载
downLoad() {
// 原生请求可替换成对应封装后请求成功的回调中进行处理
axios.post(url, {...params}, {responseType: 'blob'}).then((res) => {
const blob = new Blob([res.data])//返回一个新的blob对象
let fileName = '模版.xls'//下载文件名
const downLoadElement = document.createElement('a')//创建a标签
downLoadElement.style.display = 'none'//a标签样式为隐藏
const href = window.URL.createObjectURL(blob)//创建window临时地址
downLoadElement.href = href//跳转地址
downLoadElement.setAttribute('download', fileName)
document.body.appendChild(downLoadElement)//将指定的dom添加的body之后
downLoadElement.click()//点击事件
document.body.removeChild(downLoadElement)//移除dom
window.URL.revokeObjectURL(href)//释放url地址
}).catch((err) => {
})
},