在开发过程中会遇到下载excel但是需要传token来验证的问题,一般情况下是用直接指向地址来实现,但是token校验没办法实现,所以就用到了blod
一般情况下:
var pathurl = process.env.VUE_APP_CUSTOMERRL_URL + 'xxx/xxxx'; window.open(pathurl, '_blank')
采用blod:
var xhr = new XMLHttpRequest();
var formData = new FormData(); xhr.open('get',process.env.VUE_APP_CUSTOMERRL_URL + 'xxx/xxxx'); xhr.setRequestHeader("Authorization",'bearer '+localStorage.getItem("access_token")); xhr.responseType = 'blob'; xhr.onload = function (e) { let blob = new Blob([xhr.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); let downloadElement = document.createElement('a'); let href = window.URL.createObjectURL(blob); //创建下载的链接 downloadElement.href = href; downloadElement.download = 'demo.xlsx'; //下载后文件名 document.body.appendChild(downloadElement); downloadElement.click(); //点击下载 document.body.removeChild(downloadElement); //下载完成移除元素 window.URL.revokeObjectURL(href); //释放掉blob对象 }; xhr.send(formData);