Home  >  Article  >  Web Front-end  >  Ajax sample code to implement download progress bar

Ajax sample code to implement download progress bar

不言
不言forward
2019-03-20 11:40:533511browse

The content of this article is about the sample code of Ajax implementation of download progress bar. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

You can change the data type of a response returned from the server by setting the responseType attribute of an XMLHttpRequest object. Available attribute values ​​are the empty string (default), "arraybuffer", "blob", "document", and "text".

The value of the response attribute will vary depending on the value of the responseType attribute. May be an ArrayBuffer, Blob, Document, string, or NULL if the request is incomplete or failed.

The new version of the XMLHttpRequest object has a progress event to return progress information when transmitting data.

It is divided into two situations: uploading and downloading. The download progress event belongs to the XMLHttpRequest object, and the upload progress event belongs to the XMLHttpRequest.upload object.

1. Front-end code:

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. Backend processing interface

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);
            }
        }

Notice ::

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

When writing the http header, append "Content-Length" and Content-Encoding,

In this way, the event.lengthComputable value of the progress event on the JS side will be true, and event.total will be in the data Get the value before the transmission is completed,

Otherwise the event.lengthComputable value will return false, and the event.total value will be 0 before the data is completed.

This article is all over here. For more other exciting content, you can pay attention to the JavaScript Tutorial Video column on the PHP Chinese website!

The above is the detailed content of Ajax sample code to implement download progress bar. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete