Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network error on generated download in Chrome

in my web app, I want to provide a download for a message log. This is done by the following javascript function:

let download = (content, filename) => {
    let uriContent = "data:application/octet-stream;charset=utf-8;base64," + btoa(content);
    let link = document.createElement('a');
    link.setAttribute('href', uriContent);
    link.setAttribute('download', filename);
    let event = new MouseEvent('click');
    link.dispatchEvent(event);
};

The function is executed by a mouse click and works fine in most cases.

However, when the file becomes a little bigger ( > ~3MB), the download fails in Chrome with a network error.

The same download works fine in other browsers like Firefox. Incognito mode did not solve the issue.

Can I change something in my code to make the download work? Or is this some bug (or feature) of Chrome that prevents the download?

like image 521
Niels Avatar asked Oct 09 '18 13:10

Niels


1 Answers

There is a limit of (slightly less than) 2MB. See https://bugs.chromium.org/p/chromium/issues/detail?id=69227

You can workaround it using blob urls. https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

let download = (content, filename) => {
    let uriContent = URL.createObjectURL(new Blob([content], {type : 'text/plain'}));
    let link = document.createElement('a');
    link.setAttribute('href', uriContent);
    link.setAttribute('download', filename);
    let event = new MouseEvent('click');
    link.dispatchEvent(event);
};
like image 76
Simon Paris Avatar answered Sep 21 '22 13:09

Simon Paris