登录  /  注册
首页 > web前端 > js教程 > 正文

Ajax实现下载进度条的示例代码

不言
发布: 2019-03-20 11:40:53
转载
3320人浏览过

本篇文章给大家带来的内容是关于ajax实现下载进度条的示例代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

可以通过设置一个XMLHttpRequest对象的 responseType 属性来改变一个从服务器上返回的响应的数据类型。可用的属性值为空字符串 (默认), "arraybuffer", "blob", "document", 和 "text".

response 属性的值会根据 responseType 属性的值的不同而不同, 可能会是一个 ArrayBuffer, Blob, Document, string,或者为NULL(如果请求未完成或失败)。

新版本的 XMLHttpRequest 对象,传送数据的时候,有一个 progress 事件,用来返回进度信息。

它分成 上传 和 下载 两种情况。下载的 progress 事件属于 XMLHttpRequest 对象,上传的 progres s事件属于 XMLHttpRequest.upload 对象。

 1、前端代码:

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时需要传递            
            //监听进度事件 
            xhr.addEventListener("progress", uploadProgress, false);
            xhr.addEventListener("load", uploadComplete, false);
            xhr.addEventListener("error", uploadFailed, false);
            xhr.addEventListener("abort", uploadCanceled, 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");
        }   
        function uploadProgress(evt) {
            if (evt.lengthComputable) {          /*后端的主要时间消耗都在查询数据和生成文件,所以可以设置默认值,直到真正到达下载的进度,再开始走进度条*/
                var percent = Math.round(evt.loaded * 100 / evt.total);
                                 
                document.getElementById('progress').innerHTML = percent.toFixed(2) + '%';
                document.getElementById('progress').style.width = percent.toFixed(2) + '%';
            }else {
                document.getElementById('progress').innerHTML = 'unable to compute';
            }
        }
        function uploadComplete(evt) {
            /* 服务器端返回响应时候触发event事件*/
            document.getElementById('result').innerHTML = evt.target.responseText;
        }
        function uploadFailed(evt) {
            alert("There was an error attempting to upload the file.");
        }
        function uploadCanceled(evt) {
            alert("The upload has been canceled by the user or the browser dropped the connection.");
        }
登录后复制

2、后台处理接口

public void aaa()
        {            
            string result = string.Empty;
            for (int i = 1; i <= 6000; i++)
            {
                result += i.ToString();
                int len = result.Length;
                Response.Headers.Add("Content-Length", len.ToString());
                Response.Headers.Add("Content-Encoding", "UTF-8");
                Response.Write(result);
            }
        }
登录后复制

注意到 ::

Response.Headers.Add("Content-Length", len.ToString());
Response.Headers.Add("Content-Encoding", "UTF-8");

写出 http 头时候,附加 “Content-Length”和Content-Encoding,

这样 JS 端的 progress 事件的 event.lengthComputable 值才会为 true, event.total 才会在数据传输完毕之前取得值,

否则 event.lengthComputable 值会返回 false, event.total 在数据完成之前值都是0。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript教程视频栏目!

以上就是Ajax实现下载进度条的示例代码的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号