[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/
博客版权:如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。
分类:
[Js/Jquery]
标签:
XMLHttpRequest
, download
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
2015-04-11 rest api方式实现对文档库的管理