6

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?

amrutha varshini
  • 121
  • 2
  • 2
  • 7

1 Answers1

6

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();
}
  • 1
    Some explanation would improve your answer. – de. Jul 15 '21 at 09:51
  • Thank you for the code. But I am not sure what to add in onProgress function. I want indicate user that downloading is started. But i dont want to lock the screen by displaying some loader. Cant I show the download progress in the browsers default download pop up, that appear on file download. – amrutha varshini Jul 15 '21 at 15:23
  • For example: var progress = document.createElement("p"); progress.innerText = "Downloaded: " + pr.loaded + "/" + pr.total; document.body.appendChild(progress); – MyNameIsKitsune Jul 15 '21 at 15:30
  • Thank you. Can I know why the default browser downloading function not working? – amrutha varshini Jul 15 '21 at 16:32
  • https://developer.mozilla.org/en-US/docs/Web/API/Blob#browser_compatibility – MyNameIsKitsune Jul 15 '21 at 16:45