用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事件
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
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
评论
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>
添加评论
分类
琐碎文字 As3&Flex RIA UG English CodingArt C++ PHP Webserver E音乐盒 Unity3d C# JS&Html5 Tools mobile golang AI 最近发表
- claude code / codex的一些配置(2026年5月5日 17:38:10)
- 2026年5月5日(2026年5月5日 17:27:39)
- js的锁以及异步调用相关(2024年11月30日 10:58:51)
- golang学习之函数/方法/接口(2022年1月6日 17:50:24)
- golang学习之零值(2022年1月6日 16:38:10)
- hello, 2018(2018年1月15日 22:47:25)
- 字体类型名词解释(2015年1月18日 11:29:14)
- 获取mysql表注释以及列注释(2014年11月13日 15:56:32)
- php连接ms sql数据库的一些问题(2014年9月15日 20:32:14)
- virtualbox虚拟网络:NAT&bridge桥接网络(2014年8月25日 22:51:35)
最近回复