微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用javascript显示文件下载进度?

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。