Ajax实现进度条
程序员文章站
2022-04-14 18:42:52
/* *@url --string下载路径 *@filename --string文件名称*/ downLoadProcess(url,filename){ filename = filename || 'xxx.csv'; // 创建xhr对象 var req = new XMLHttpReque ......
/*
*@url --string下载路径
*@filename --string文件名称
*/
downloadprocess(url,filename){
filename = filename || 'xxx.csv';
// 创建xhr对象
var req = new xmlhttprequest();
//向服务器发送请求 open() send()
req.open("post", url, true); //(method-get/post ,url, 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");
}