文件下载
文件下载是一个比较常见的需求,最近在实现移动端文件下载时遇到了下载文件出现CORS的问题。
解决路程:起初,发现是后端的代理没有配置好;后端代理映射配置好后,发现移动端文件下载还是不行,后来发现pc端下载是成功的;
这就很奇怪了呀(陷入了思维定势,查看代码会自动忽略某些东西,这个时候就应该摇人了)。最后发现代码有问题,url带有http,下载请求时改写了请求头,携带了token。。。
上正确代码
axios({
//
url: file.fileUrl,
method: 'get',
headers: { //这里我把token信息去掉了
'Content-Type': 'application/x-www-form-urlencoded',
},
responseType: 'blob',
// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: this.onDownloadProgress,
})
.then((res) => {
const { data, headers } = res
const fileName = headers['content-disposition'].replace(
/\w+;filename=(.*)/,
'$1'
)
const blob = new Blob([data], { type: headers['content-type'] })
const url = window.URL.createObjectURL(blob)
this.dom.href = url //这个dom保存的是a链接dom对象
this.dom.download = decodeURI(fileName)
this.dom.style.display = 'none'
document.body.appendChild(this.dom)
this.dom.click()
})
.catch((err) => {
console.log(err)
})
附:fetch请求
fetch请求下载文件和axios下载都类似,先是获取blob对象,然后利用a链接或者window下载。当然,如果后端给的是一个带http的url没有其他需求可以直接使用a链接和window对象下载文件。
fetch(url, {
headers: new Headers({
Origin: location.origin,
}),
mode: "cors",
})
.then((res) => res.blob())
.then((blob) => {
const blobUrl = window.URL.createObjectURL(blob);
if (isIE() || isEdge()) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
const url = window.URL || window.webkitURL || window.moxURL;
const downloadHref = url.createObjectURL(blob);
const downloadLink = document.createElement("a");
downloadLink.href = downloadHref;
downloadLink.download = fileName;
downloadLink.click();
}
window.URL.revokeObjectURL(blobUrl);
});
阿巴阿巴…