如何使用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();
}