I am trying to download a file using web link with Javascript's XMLHttpRequest Object.I am not able to find out whether is it possible to pause a download and later resume it?
No. It is not possible. Some suggest to just call abort()
on your xhr object and save the received blob in some variable and so on but unfortunately, that's just their wish because as soon as the abort()
is called the xhr object is discarded with all the data it previously downloaded. There is no way you can save the downloaded data in the middle of running xhr. Progress
event of xhr will just give you the info about the bytes downloaded but not the actual data downloaded. Neither this downloaded data is cached so we cannot resume it.
However, there is one way around to pause the xhr and resume later is to call xhr with Bytes-Range Header. But for this to work, your server needs to accept Byte-Range Header. Most of today's server does it by default.
request.responseType = 'blob'; //<--I set responseType as Blob
request.setRequestHeader('Range', `bytes=${bytesFrom}-${bytesTo}`);
You will need to call complete xhr requests from open()
method to onload
event with bytesFrom & bytesTo, save the received chunk in an array. Then repeat the requests with Next bytes until your bytesTo are equal to the totalBytes of file. Each time receive the chunk in onload
event, save it in array.
chunksArray.push(this.reponse);
When all of your chunks are received, you can call
let downloadedFile = new Blob(chunksArray);
To get this Blob in your use, you can create a URL
let downloadedFileURL = URL.createObjectURL(downloadedFile);
So, unless you don't call xhr with Next bytes, your XHR is paused and when you call xhr request with Next bytes, it resumes.