Reputation: 79
Below code is showing a "file not found" error in Chrome but the same code works for some other environments in chrome, and after adding some time delay it was working.
Kindly advise about the reason for the required time delay in my local environment.
var a = document.createElement('a');
a.style = "display: none";
var blob = new Blob(data, {type: "application/octet-stream"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
Upvotes: 3
Views: 7346
Reputation: 79
i have added setimeout like below now it working fine
setTimeout(function(){ window.URL.revokeObjectURL(url); }, 3000);
Upvotes: 2
Reputation: 136698
Revoking a blob:// URI is a synchronous operation, downloading a file on the other hand is not.
Even though the data can be in memory and thus downloaded really fast, it is not always the case. The Blob's data may not even be in a single place, for instance some blobParts could be in memory, some others on user's disk or even in a shared folder access through a network. Also simply requesting the OS for access to write can actually be made asynchronously.
So by the time you call revokeObjectURL
, the browser may still haven't had the time to write your file to disk and when it tries to do so, or to access a new blobPart, there is no more pointers available at the provided address.
There is unfortunately no event letting us know when this writing to disk is done, at least not until the native-file-system API becomes official, so the best we can do for now is to wait a fair amount of time before revoking the blob:// URI.
For reference, FileSaver.js does wait 40s.
Upvotes: 5