簡體   English   中英

如何使用javascript顯示文件下載進度?

[英]How show file download progress using javascript?

我正在使用以下代碼將文件下載到瀏覽器。

function UserAction() {
 
 var Url = " ";

  var postData = new FormData();
  var xhr = new XMLHttpRequest();
  xhr.open('GET', Url, true);
  xhr.responseType = 'blob';
  xhr.onload = function (e) {
    var blob = xhr.response;
    this.saveOrOpenBlob(blob,blobName);
  }.bind(this)
  xhr.send(postData);

}

function saveOrOpenBlob(blob,blobName) {
  //var assetRecord = this.getAssetRecord();
  var fileName = blobName;
  var tempEl = document.createElement("a");
    document.body.appendChild(tempEl);
    tempEl.style = "display: none";
      url = window.URL.createObjectURL(blob);
      tempEl.href = url;
      tempEl.download = fileName;
      tempEl.click();
  window.URL.revokeObjectURL(url);
}

我想顯示下載進度,我沒有使用任何 html 代碼。 我的應用程序具有接受 javascript 操作的標准按鈕。 我沒有任何自定義用戶界面。

在當前條件下,如果文件是大文件,用戶將不知道文件是否正在下載。

我怎樣才能做到這一點?

用這個:

function saveOrOpenBlob(url, blobName) {
    var blob;
    var xmlHTTP = new XMLHttpRequest();
    xmlHTTP.open('GET', url, true);
    xmlHTTP.responseType = 'arraybuffer';
    xmlHTTP.onload = function(e) {
        blob = new Blob([this.response]);   
    };
    xmlHTTP.onprogress = function(pr) {
        //pr.loaded - current state
        //pr.total  - max
    };
    xmlHTTP.onloadend = function(e){
        var fileName = blobName;
        var tempEl = document.createElement("a");
        document.body.appendChild(tempEl);
        tempEl.style = "display: none";
        url = window.URL.createObjectURL(blob);
        tempEl.href = url;
        tempEl.download = fileName;
        tempEl.click();
        window.URL.revokeObjectURL(url);
    }
    xmlHTTP.send();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM