paulwong

          AJAX下載+監(jiān)控進度+保存文件

          全程用AJAX下載文件,并顯示下載進度,之后保存文件。

          HTML5文件:

          <!DOCTYPE html>
          <html>
          <head>
              <title>XMLHttpRequest Download Progress</title>
          </head>
          <body>
              <progress id="p"></progress>
              <input type="button" onclick="downloadAndSave();" value="Download"/>
              <script>
                  
          function downloadAndSave()
                  {
                      
          var progressBar = document.getElementById('p'), xhr = new XMLHttpRequest();
                      xhr.open('GET', '
          2');
                      xhr.responseType 
          = "arraybuffer";
                      xhr.onprogress 
          = function(event) {
                          
          if(event.lengthComputable) {
                              progressBar.max 
          = event.total;
                              progressBar.value 
          = event.loaded;
                          }
                      };
                      xhr.onloadend 
          = function(event) {
                          progressBar.value 
          = event.loaded;
                          saveByeToFile('
          2', xhr.response);
                      };
                      xhr.send();
                  }
                  
                  
          function saveByeToFile(name, arrayBuffer) {
                      
          var byteArray = new Uint8Array(arrayBuffer);
                      
          var a = window.document.createElement('a');

                      a.href 
          = window.URL.createObjectURL(new Blob([ byteArray ], {
                          type : 'application
          /octet-stream'
                      }));
                      a.download 
          = name;

                      
          // Append anchor to body.
                      document.body.appendChild(a)
                      a.click();

                      
          // Remove anchor from body
                      document.body.removeChild(a)
                  }
              
          </script>
          </body>
          <html>

          posted on 2015-08-06 19:17 paulwong 閱讀(1141) 評論(0)  編輯  收藏 所屬分類: HTML5

          主站蜘蛛池模板: 公主岭市| 阿巴嘎旗| 横山县| 建平县| 万载县| 纳雍县| 长岭县| 龙游县| 盐源县| 南和县| 浮梁县| 佛山市| 岑溪市| 宜昌市| 伊金霍洛旗| 盐津县| 安化县| 崇义县| 新晃| 乐都县| 兴宁市| 宝丰县| 随州市| 永春县| 墨脱县| 清丰县| 唐海县| 韶关市| 会宁县| 天全县| 刚察县| 高邮市| 舟曲县| 榆社县| 兴业县| 宁乡县| 蒙山县| 璧山县| 德州市| 理塘县| 中方县|