<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">/
@url --string下载路径
@filename --string文件名称
/
<pre class="brush:javascript;gutter:true;">
downLoadProcess(url,filename){
filename = filename || 'xxx.csv';
// 创建xhr对象
var req = new XMLHttpRequest();
//向服务器发送请求 open() send()
req.open("POST",url,true); //(method-GET/POST,async)
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");//POST时需要传递
//监听进度事件
req.addEventListener("progress",function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
$("#progressing").html((percentComplete 100) + "%");
}
},false);
/
XMLHttpRequest 的 responseType 属性
一个枚举类型的属性,返回响应数据的类型,只能设置异步的请求
1、'' -- DOMString (默认); UTF-16
2、arraybuffer -- arraybuffer对象,即类型化数组
3、blob -- Blob对象, 二进制大数据对象
4、document -- Document对象
5、json
6、text
*/
//设置返回数据的类型
req.responseType = "blob";
req.onreadystatechange = function () { //同步的请求无需onreadystatechange
if (req.readyState === 4 && req.status === 200) {
var filename = $(that).data('filename');
if (typeof window.chrome !== 'undefined') {
// Chrome version
var link = document.createElement('a');
link.href = window.URL.createObjectURL(req.response);
link.download = filename;
link.click();
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE version
var blob = new Blob([req.response],{ type: 'application/force-download' });
window.navigator.msSaveBlob(blob,filename);
} else {
// Firefox version
var file = new File([req.response],filename,{ type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
}
};
req.send("fname=Henry&lname=Ford");
}</pre>