用ajax下载文件
sshong 发表于2013年9月24日 17:35:08 更新于2013年9月24日 17:40:18
1、用原生xmlhttprequest
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
标签:无分类:JS&Html5阅读:4841
评论
Judi Indonesia2014年11月4日 18:34
I've Been Absent For A While, But Now I Remember Why I Used To Love This Blog. Thank You, I Will Try And Check Back More Often. How Frequently You Update Your Site?  <a href=http://judiindonesiaonline.com/>Judi Indonesia Online Terbaik</a>
添加评论
您的大名,限长10汉字,20英文(*)
电子信箱(*)
您的网站
正文,限长500汉字,1000英文(*)
验证码(*) 单击刷新验证码
联系我
博客订阅