amrutha varshini
amrutha varshini

Reputation: 131

How show file download progress using javascript?

I am using below code to download the file to browser.

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);
}

I want to display the download progress, I am not using any html code. My application has standard button which accept javascript action. I dont have any custom ui.

With current condition user will not know whether the file is downloading or not if it is a large file.

How can I achieve this?

Upvotes: 7

Views: 16314

Answers (1)

MyNameIsKitsune
MyNameIsKitsune

Reputation: 196

Use this:

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();
}

Upvotes: 7

Related Questions