[Javascript]XMLHttpRequest对象实现下载进度条
摘要
可以通过设置一个XMLHttpRequest对象的responseType属性来改变一个从服务器上返回的响应的数据类型。可用的属性值为空字符串 (默认), "arraybuffer", "blob", "document", 和 "text". response属性的值会根据responseType属性的值的不同而不同, 可能会是一个 ArrayBuffer, Blob, Document, string,或者为NULL(如果请求未完成或失败)。
新版本的XMLHttpRequest对象,传送数据的时候,有一个progress事件,用来返回进度信息。
它分成上传和下载两种情况。下载的progress事件属于XMLHttpRequest对象,上传的progress事件属于XMLHttpRequest.upload对象。
一个例子
服务端以一个一般处理程序来处理下载的请求。
/// <summary> /// download 的摘要说明 /// </summary> public class download : IHttpHandler { public void ProcessRequest(HttpContext context) { string fileName = "1.docx";//客户端保存的文件名 string filePath = context.Server.MapPath("~/file/" + fileName);//路径 //以字符流的形式下载文件 FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); context.Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 context.Response.AddHeader("Content-Length", bytes.Length.ToString()); context.Response.AddHeader("Content-Transfer-Encoding", "Binary"); context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); context.Response.BinaryWrite(bytes); context.Response.Flush(); context.Response.End(); } public bool IsReusable { get { return false; } } }
js
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="jquery-2.1.1.min.js"></script> <title></title> </head> <body> <div id="a1" data-filename="1.docx">下载</div> <div id="progressing"></div> <script> $('#a1').click(function () { var that = this; var page_url = 'download.ashx'; var req = new XMLHttpRequest(); req.open("POST", page_url, true); //监听进度事件 req.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; console.log(percentComplete); $("#progressing").html((percentComplete * 100) + "%"); } }, false); req.responseType = "blob"; req.onreadystatechange = function () { 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(); }); </script> </body> </html>
测试
XMLHttpRequest Level 2 使用指南
关于XMLHttpRequest新规范可以查看这篇文章的介绍
http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html
-
博客地址:http://www.cnblogs.com/wolf-sun/
博客版权:如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。