在JS中如何发送ajax请求,并且解析后台返回的Blob类型数据,将数据转换为文件导出,附带兼容IE8等浏览器
普通的jQuery中的ajax请求后台,并不能处理Blob类型的数据,这里用的原生的XMLHttpRequest请求后台
var xhr = new XMLHttpRequest(); xhr.open("get", url, true); xhr.responseType = "blob"; xhr.onload = function() { if (this.status == 200) { var blob = this.response; if(blob.type == "text/html"){ tip("出错"); return false } var fileName = filename; if(window.navigator.msSaveOrOpenBlob){ // IE浏览器下 navigator.msSaveBlob(blob, fileName); } else { var link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); window.URL.revokeObjectURL(link.href); } }else{ iframe.tip("请求错误!"); } } xhr.onloadend = function(res){ } xhr.send();
可参考:ajax处理流数据