zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    ubuntu之路——day8.4 Adam自适应矩估计算法
    ubuntu之路——day8.3 RMSprop
    ubuntu之路——day8.2 深度学习优化算法之指数加权平均与偏差修正,以及基于指数加权移动平均法的动量梯度下降法
    ubuntu之路——day8.1 深度学习优化算法之mini-batch梯度下降法
    ubuntu之路——day7.4 梯度爆炸和梯度消失、初始化权重、梯度的数值逼近和梯度检验
    redis作为mysql的缓存服务器(读写分离)
    阿里云服务器上配置并使用: PHP + Redis + Mysql 从配置到使用
    小程序开发测试教程
    使用PHP并发执行任务–curl_multi应用
    PHP返回变量或数组的字符串表示:var_export()
  • 原文地址:https://www.cnblogs.com/wolf-sun/p/6693367.html
Copyright © 2011-2022 走看看