原生Ajax下载excel(带token)

首先确定后端返回的是文件流

let xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.responseType = 'blob';
xhr.setRequestHeader('Authorization', token)
xhr.onload = function(e) {
	console.log(this.response);
	var blob = this.response;
	var reader = new FileReader();
	reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
	reader.onload = function(e) {
		// 转换完成,创建一个a标签用于下载
		var a = document.createElement('a');
		a.download = (new Date()).getTime() + '.xls';
		a.href = e.target.result;
		$("body").append(a); // 修复firefox中无法触发click
		a.click();
		$(a).remove();
	}
}
xhr.send();

猜你喜欢

转载自blog.csdn.net/A88552211/article/details/123407224