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);
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);
Share
Improve this question
edited Jul 27, 2020 at 7:00
Kaiido
138k14 gold badges259 silver badges324 bronze badges
asked Jul 27, 2020 at 6:37
user1777192user1777192
791 silver badge5 bronze badges
3
- @CodyGray there is largely enough information to see what's wrong here. – Kaiido Commented Jul 27, 2020 at 6:47
- @CodyGray If you know how this API works it is crystal clear that they do revoke the blob URI before the browser could download it. No need for an edit, it's already an MCVE. – Kaiido Commented Jul 27, 2020 at 6:48
- Please show the code without the time delay and with the time delay – gboffi Commented Jul 27, 2020 at 8:08
2 Answers
Reset to default 5Revoking 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 bees 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.
i have added setimeout like below now it working fine
setTimeout(function(){ window.URL.revokeObjectURL(url); }, 3000);