paulwong

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

          全程用AJAX下載文件,并顯示下載進(jìn)度,之后保存文件。

          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

          主站蜘蛛池模板: 靖州| 屯门区| 保靖县| 德江县| 西畴县| 贵溪市| 绍兴县| 丰城市| 平武县| 信丰县| 西青区| 合水县| 黎城县| 健康| 合作市| 巴塘县| 沂南县| 贵溪市| 岳普湖县| 卓尼县| 韩城市| 襄城县| 内丘县| 郧西县| 呼伦贝尔市| 晴隆县| 兴城市| 宣威市| 凌源市| 浏阳市| 互助| 日照市| 永德县| 乌鲁木齐市| 堆龙德庆县| 辽阳市| 漳浦县| 瑞昌市| 儋州市| 小金县| 大英县|