js 处理返回文件流

今天在处理excel下载时遇到的一个问题,在这里记录一下

项目里在处理excel下载时,客户那边api返回的是文件流,并且这边发送请求时需要设置请求头验证Token,而ajax不能接收处理文件流,所以找了另一种方法

<script type="text/javascript">
	function download() {

	    var xmlResquest = new XMLHttpRequest();
	    xmlResquest.open("POST", "/eksoft/fileUpload/download", true);
	    xmlResquest.setRequestHeader("Content-type", "application/json");
	    xmlResquest.setRequestHeader("Authorization", "Bearer 6cda86e3-ba1c-4737-972c-f815304932ee");
	    xmlResquest.responseType = "blob";
	    xmlResquest.onload = function (oEvent) {
			
                var content = xmlResquest.response;
                var elink = document.createElement('a');
                elink.download = "test.xlsx";
                elink.style.display = 'none';
                var blob = new Blob([content]);
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            };
            xmlResquest.send();
	}
</script>

没有更多推荐了,返回首页