当后端返回的接口数据为
普通的URL下载就不好用了如
export function gettFile(url, params, fileName) {
const blob = new Blob([url], {
type: "application/msword",
});
const objectUrl = url;
const link = document.createElement("a"); //我们用模拟q标签点击事件
const fname = fileName; //下载文件的名字
link.href = objectUrl;
link.setAttribute("download", fname);
document.body.appendChild(link);
link.click(); //点击
document.body.removeChild(link); // 下载完成移除元素
window.URL.revokeObjectURL(URL); // 释放掉blob对象
}
要先下载文件流再处理,
用decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1]) 自动获取文件名
export function gettFile(url, params, filename) {
return new Promise((resolve, reject) => {
axios
.post(url, params, {
headers: {
'token': window.localStorage.getItem('token') || ''
},
responseType: 'blob'
})
.then((res) => {
console.log(res,res.data);//这里检查后端返回的内容是res还是包了data 打印检查一下
const blob = new Blob([res])
const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
if ('download' in document.createElement('a')) {
// 非IE
const elink = document.createElement('a')
elink.download = _fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL
document.body.removeChild(elink)
} else {
// IE10+
navigator.msSaveBlob(blob, _fileName)
}
})
.catch((err) => {
reject(err.data)
})
})
}