美文网首页
原生ajax 兼容ie11 下载excel文件

原生ajax 兼容ie11 下载excel文件

作者: aaagu1234 | 来源:发表于2020-05-28 16:03 被阅读0次

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();
} 

相关文章

网友评论

      本文标题:原生ajax 兼容ie11 下载excel文件

      本文链接:https://www.haomeiwen.com/subject/rfsaahtx.html