[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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM