xhr实现下载文件携带token
问题:传统方式href带参数后边直接添加键值对即可,但是无法传token,但是下载接口不验证token又是不安全的,所以需要添加token解决方式:使用xhr实现下载文件// 下载文件,比如:pdf、doc、excel等export function downloadFile(filePath,RemotePath, fileName,type) {const baseURL = process.
·
问题:
传统方式href带参数后边直接添加键值对即可,但是无法传token,但是下载接口不验证token又是不安全的,所以需要添加token
解决方式:
使用xhr实现下载文件
// 下载文件,比如:pdf、doc、excel等
export function downloadFile(filePath,RemotePath, fileName,type) {
const baseURL = process.env.VUE_APP_BASE_API
const 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 = url
a.download = fileName + type // 文件名
}
a.click()
window.URL.revokeObjectURL(url)
}
xhr.send()
}
// 下载文件,普通文件下载
export function download(filePath,fileName) {
const baseURL = process.env.VUE_APP_BASE_API
const baseUrl = baseURL + '/common/download?filePath=' + filePath
var 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.response
var a = document.createElement('a')
var url = window.URL.createObjectURL(blob)
a.href = url
a.download = fileName // 文件名
}
a.click()
window.URL.revokeObjectURL(url)
}
xhr.send()
}
其实,也可以直接调用axios来实现,具体代码感兴趣的朋友可以自行研究下
ps:继续来更新啦~
这块代码写了很久,后来自己也发现有问题
左边代码是修改之前的,这样写的话,发现在火狐浏览器上下载pdf文件是直接打开而不是下载,但是我改成右边代码就好使了,我也没有仔细去研究原因,就暂时先解决吧
更多推荐
所有评论(0)