当服务器计算excel ,返回数据超级慢的情况下,需要加入 loadding 显示,采用 xhr.responseType = 'arraybuffer'
设置类型,进行 发送请求,回调回来的数据为 二进制流,设置 window.navigator.msSaveOrOpenBlob
支持 ie10+,搜狗浏览器兼容模式场景!
sendDown(urls, callback) {
let that = this;
var cur = Promise.resolve();
urls.forEach(function(url) {
cur = cur.then(function() {
return that.downFile(url, callback);
});
});
return cur;
},
/**
*
* @param {下载接口请求} url
* @param {*} callback
*/
downFile(url, callback) {
let filename = '';
let xhr = '';
return new Promise(function(resolve, reject) {
filename = url.substring(url.lastIndexOf('/') + 1).split('?')[0];
xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(xhr);
};
xhr.onerror = reject;
xhr.open('GET', url);
try {
xhr.responseType = 'arraybuffer'; //arraybuffer , blob
} catch (err) {
console.error(err);
}
xhr.send();
}).then(xhr => {
var blob = new Blob([xhr.response], { type: 'application/vnd.ms-excel' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, 'data.xlsx');
} else {
var downloadUrl = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = downloadUrl;
a.download = 'data.xlsx';
document.body.appendChild(a);
a.click();
}
return callback && callback(xhr);
});
},
appendQuery(data) {
var arr = [];
for (var i in data) {
//特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join('&');
},
调用
let URL = that.appendQuery(data.param);
this.sendDown(
[`${utils.url.curr}/sylla/phr-ui/bonuspm/report/export?${URL}`],
req => {
that.loaddingSpinShow = false;
},
);