xhr实现下载文件携带token

问题:

传统方式href带参数后边直接添加键值对即可,但是无法传token,但是下载接口不验证token又是不安全的,所以需要添加token

解决方式:

使用xhr实现下载文件

// 下载文件,比如:pdf、doc、excel等
export function downloadFile(filePath,RemotePath, fileName,type) {const baseURL = process.env.VUE_APP_BASE_APIconst baseUrl = baseURL + '/common/download?filePath=' + encodeURI(filePath) + '&remotePath=' + encodeURI(RemotePath) + '&fileName=' + encodeURI(fileName)var xhr = new XMLHttpRequest()xhr.open('get', baseUrl, true) // get、post都可xhr.responseType = 'blob' // 转换流xhr.setRequestHeader('Authorization', 'Bearer ' + getToken()) // token键值对var fileType = getFileType(type);xhr.onload = function() {if (this.status == 200) {const blob = new Blob([this.response], { type: fileType })var a = document.createElement('a')var url = window.URL.createObjectURL(blob)a.href = urla.download = fileName + type // 文件名}a.click()window.URL.revokeObjectURL(url)}xhr.send()
}
// 下载文件,普通文件下载
export function download(filePath,fileName) {const baseURL = process.env.VUE_APP_BASE_APIconst baseUrl = baseURL + '/common/download?filePath=' + filePathvar xhr = new XMLHttpRequest()xhr.open('get', baseUrl, true) // get、post都可xhr.responseType = 'blob' // 转换流xhr.setRequestHeader('Authorization', 'Bearer ' + getToken()) // token键值对xhr.onload = function() {if (this.status == 200) {var blob = this.responsevar a = document.createElement('a')var url = window.URL.createObjectURL(blob)a.href = urla.download = fileName // 文件名}a.click()window.URL.revokeObjectURL(url)}xhr.send()}

其实,也可以直接调用axios来实现,具体代码感兴趣的朋友可以自行研究下

ps:继续来更新啦~

这块代码写了很久,后来自己也发现有问题

左边代码是修改之前的,这样写的话,发现在火狐浏览器上下载pdf文件是直接打开而不是下载,但是我改成右边代码就好使了,我也没有仔细去研究原因,就暂时先解决吧 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部