function downloadRequest(url, name){
var xhr=new XMLHttpRequest();
xhr.open('GET',url,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('token', Vue.cookie.get('token'));
xhr.responseType = 'blob';
xhr.onreadystatechange=function(){
// readyState == 4说明请求已完成
if(xhr.readyState==4){
if(xhr.status==200 || xhr.status==304){
let blob = new Blob([xhr.response], {type: "application/vnd.ms-excel;charset=utf-8"});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, name + '.xlsx');
}else{
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = name + '.xlsx'; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}
}
}
}
xhr.send();
}
网友评论