通过XmlHttpRequest实现带进度条异步下载文件

本博文源自技术群的讨论,因为网上找不到实现这样效果的的代码,而我说没问题,可以实现,因此有人质疑我是否能做到,呵呵,现将我实现代码贴出如下,希望有兴趣的同学可以继续完善:

本代码仅做技术展现,请勿探讨其他细节。。。。

<!DOCTYPE html>
<html>
<head>
    <title>Test XMLHttpRequest download with progress bar</title>
    <script type="text/javascript" src="/js/jquery-2.2.0.js"></script>   
</head>
<body>
    <div style="width:600px;margin:10px auto;background-color:#fff;">
        <input id="DownLoadFile" type="button" value="DownLoadFile" />
        <div style="height:8px;width:100px;border-radius:3px;border:1px solid #eee;">
            <div id="progressBar" style="background-color:#ccf;height:6px;width:0px;border-radius:3px;border:0px;"></div>
        </div>
    </div>
  </body>
</html>
<script type="text/javascript">    
    var onProgress = function (e) {
        if (e.lengthComputable) {
            document.getElementById("progressBar").style.width = Math.round(e.loaded * 100 / e.total) + 'px';
        }
    };
    $(function () {
        $('#DownLoadFile').on('click', function () {
            var xhr = new XMLHttpRequest();
            xhr.onprogress = onProgress; //下载监听
            xhr.responseType = "blob";
            xhr.open("GET", "http://localhost:36348/Doc/TortoiseSVN-1.9.4.27285-x64.zip", true);
            xhr.onreadystatechange = function (e) {
                if (this.readyState == 4 && this.status == 200) {
                    var response = this.response;
                    var URL = window.URL || window.webkitURL || window;
                    var link = document.createElement('a');
                    link.href = URL.createObjectURL(response);
                    link.download = 'TestDownLoad';
                    //link.click(); //ie及firefox不响应识别模拟点击事件
                    //下面方法,edge,chrome和firefox都兼容
                    var event = document.createEvent('MouseEvents');
                    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    link.dispatchEvent(event);
                }
            }
            xhr.send(null);
            return false;
        });
    });
</script>

  

  运行截图:

接收文件展开截图

注意:大家再现效果的时候,选择下载的文件不能太小,否则进度条不会显示!!

posted on 2017-01-04 11:14  丰云  阅读(765)  评论(0编辑  收藏  举报

导航