>  기사  >  웹 프론트엔드  >  다운로드 진행률 표시줄을 구현하는 Ajax 샘플 코드

다운로드 진행률 표시줄을 구현하는 Ajax 샘플 코드

不言
不言앞으로
2019-03-20 11:40:533433검색

이 기사의 내용은 다운로드 진행률 표시줄의 Ajax 구현 샘플 코드에 관한 것입니다. 이는 특정 참조 값을 가지고 있으므로 도움이 될 수 있습니다.

XMLHttpRequest 객체의 responseType 속성을 설정하여 서버에서 반환된 응답의 데이터 유형을 변경할 수 있습니다. 사용 가능한 속성 값은 빈 문자열(기본값), "arraybuffer", "blob", "document" 및 "text"입니다. response 속성 값은 responseType 속성 값에 따라 달라집니다. 요청이 불완전하거나 실패한 경우 ArrayBuffer, Blob, Document, 문자열 또는 NULL입니다.

XMLHttpRequest 객체의 새 버전에는 데이터 전송 시 진행률 정보를 반환하는 진행률 이벤트가 있습니다.

업로드와 다운로드의 두 가지 상황으로 구분됩니다. 다운로드 진행 이벤트는 XMLHttpRequest 객체에 속하고 업로드 진행 이벤트는 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을 추가합니다.

이런 방식으로 event.lengthComputable 값은 JS 측의 진행 이벤트는 true가 되며, event.total은 데이터 전송이 완료되기 전에 값을 가져옵니다. 그렇지 않으면 event.lengthComputable 값은 false를 반환하고 데이터가 완료되기 전에 event.total 값은 0이 됩니다.

이 기사는 여기까지입니다. 더 흥미로운 내용을 보려면 PHP 중국어 웹사이트의

JavaScript Tutorial Video

칼럼을 주목하세요!

위 내용은 다운로드 진행률 표시줄을 구현하는 Ajax 샘플 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제