下载方法window.open 传递token
下载方法window.open 传递token
·
前言:
前后端分离,后端下载方法增加校验,必须在header中传递token,前端之前直接使用window.open(url) 请求下载方法,直接下载,window.open 没办法在header中增加参数
解决:
function windowOpen(url,fileName){
var xhr = new XMLHttpRequest();
// var fileName = window.fileName + typeName; // 文件名称
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.setRequestHeader('token',window.localStorage.getItem('token'));
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();
}
// window.open(url) //原来的
this.windowOpen(url,'serverother.xls')
更多推荐
已为社区贡献1条内容
所有评论(0)