a.设置请求头setRequestHeader的Content-Type为你发送过去的数据,如表单或者json等
b.设置responseType为blob
c.根据content-type发送对应的数据过去
d.侦听成功响应,取到二进制的response(应该是blob对象)
e.创建blob的url
f.创建一个虚拟的a link,href指向blob的url,name,并触发click事件
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//创建隐藏的下载链接
console.log(this.response, typeof this.response);
var downloadLink = document.createElement('a');
downloadLink.style.display = 'none';
downloadLink.download = "测试.xls";
var URL = window.URL || window.webkitURL;
downloadLink.href = URL.createObjectURL(this.response);
document.body.appendChild(downloadLink);
//触发click
var event = document.createEvent("MouseEvents");
event.initMouseEvent(
"click", true, false, window, 0, 0, 0, 0, 0
, false, false, false, false, 0, null
);
downloadLink.dispatchEvent(event);
//URL.revokeObjectURL(iframe.src);
}
}
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.send($.param({name:'test'}));
2、用jquery的$.ajax。sorry,要改jquery的源码,jquery会封装隐藏掉原生的xmlhttprequest,看源码会发现,jquery只要text类型的response,并且用responseText作为最终的数据源,如果要支持blob的返回数据,参考
http://bugs.jquery.com/ticket/11461
参考:
Using jQuery's ajax method to retrieve images as a blob
w3c FileAPI
Using files from web applications
Send as Blob/ArrayBuffe
FileSaver.js