window.open 中传递Authorization header token。vue根据链接下载文件的时候传递header token 电脑版发表于:2020/9/29 18:28 #### 直接使用window.open去给一个链接下载文件是传递不了header token的 ``` window.open(baseURL + 'DownloadFile/ArchivesDownloadFile?fileId=' +row.id ) ``` 如果后端不验证token是可以这样做,但是如果要验证token就要换一种方法了。 #### 封装根据链接下载文件的方法 ``` function windowOpen(url, fileName) { var xhr = new XMLHttpRequest() xhr.open('GET', url, true) xhr.responseType = 'blob' // alert(55) xhr.setRequestHeader('Authorization', 'Bearer ' + token.value) xhr.onload = function (res) { if (this.status === 200) { var type = xhr.getResponseHeader('Content-Type') var blob = new Blob([this.response], { type: type }) if (typeof window.navigator.msSaveBlob !== 'undefined') { /* * For IE * >=IE10 */ window.navigator.msSaveBlob(blob, fileName) } else { /* * For Non-IE (chrome, firefox) */ var URL = window.URL || window.webkitURL var objectUrl = URL.createObjectURL(blob) if (fileName) { var a = document.createElement('a') if (typeof a.download === 'undefined') { window.location = objectUrl } else { a.href = objectUrl a.download = fileName document.body.appendChild(a) a.click() a.remove() } } else { window.location = objectUrl } } } } xhr.send() } ``` #### 调用封装的方法 ``` const downLoadArchive = async (e, row) => { console.log(row) // alert(row.fileName) // window.open( // baseURL + 'DownloadFile/ArchivesDownloadFile?fileId=' + row.id // ) windowOpen( baseURL + 'DownloadFile/ArchivesDownloadFile?fileId=' + row.id, row.fileName ) } ``` 注意这里要给文件名,window.open是可以不给文件名的,只给一个下载链接即可。 **下载文件的时候如果想要一个下载完成的事件,可以传递一个方法到封装的方法里边就行了** ``` windowOpen( baseURL + 'FileManager/DownloadContentByTemplate?fileId=' + row.id, row.fileName + '.xls', () => { alert('文件下载完成!') } ) ``` 封装的方法里边接收一个函数的参数,在需要的地方执行就行了 ``` function windowOpen(url, fileName, success) { const xhr = new XMLHttpRequest() xhr.open('GET', url, true) xhr.responseType = 'blob' // alert(55) xhr.setRequestHeader('Authorization', 'Bearer ' + token.value) xhr.onload = function (res) { if (this.status === 200) { const type = xhr.getResponseHeader('Content-Type') const blob = new Blob([this.response], { type: type }) if (typeof window.navigator.msSaveBlob !== 'undefined') { /* * For IE * >=IE10 */ window.navigator.msSaveBlob(blob, fileName) } else { /* * For Non-IE (chrome, firefox) */ const URL = window.URL || window.webkitURL const objectUrl = URL.createObjectURL(blob) if (fileName) { const a = document.createElement('a') if (typeof a.download === 'undefined') { window.location = objectUrl } else { a.href = objectUrl a.download = fileName document.body.appendChild(a) a.click() a.remove() } } else { window.location = objectUrl } } success() } } xhr.send() } ``` <br/> **这里获取token的方法是vue-admin-beautiful plus版本中封装的** 参考:https://www.tnblog.net/aojiancc2/article/details/7970