1

Using the following code from Using HTML5/JavaScript to generate and save a file :

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

download('test.txt', 'Hello world!');

I also used a blob but no luck:

var fileContent = String.raw`test`;
var fileName = 'sampleFile.txt';

const blob = new Blob([fileContent], { type: 'text/plain' });
const a = document.createElement('a');
a.setAttribute('download', fileName);
a.setAttribute('href', window.URL.createObjectURL(blob));
a.click();

I am encountering a limit on downloading a string to a file through a hyperlink. I have found in Chrome that if the amount of characters exceed 65535 the hyperlink disappears or on firefox, a 0 bytes file is downloaded.

Is there a way to circumvent this limit? Or perhaps a different way in pure javascript/html to download the file where this limit doesn't exist or is increased?

tutu
  • 673
  • 2
  • 13
  • 31
  • Does this answer your question? [Problems downloading big file(max 15 mb) on google chrome](https://stackoverflow.com/questions/38781968/problems-downloading-big-filemax-15-mb-on-google-chrome) – Nils Kähler Jun 14 '22 at 10:43
  • @NilsKähler I tried to use a blob but no luck, I am having the same problem. I have updated my main post with the blob version – tutu Jun 14 '22 at 20:29
  • I take it that the string passed to encodeuricomponent is too long? Edit: oops, I doubt "Hello world!" is too long – Brandon Piña Jun 14 '22 at 22:33
  • @BrandonPiña correct, replace the 'Hello World!' with a string of a bit more then 500.000 characters – tutu Jun 15 '22 at 06:17
  • Does this not work for you? https://jsfiddle.net/df4eu7z5/ it downloads fine for me, and the text contains 720720 characters. – Nils Kähler Jun 15 '22 at 12:45
  • Normally i'd see if it's possible to find an alternative to encodeURIcomponent that uses streams instead of all at once. Otherwise, try splitting your string, running encodeURIcomponent on each slice and then concatenate them together. No idea if your browser might have a fit though – Brandon Piña Jun 15 '22 at 20:45
  • 1
    @NilsKähler I am able to download that file works fine for me. So I am starting to think it's the platform where I use the code is the issue. The platform is a SSRS report where I use the javascript code to download text from a column. The string is over 700.000 characters in size and the hyperlink simply is not clickable any more. Once I truncate the string to 65535 the hyperlink works. I guess I will have to direct my search towards SSRS config or something – tutu Jun 17 '22 at 07:30

0 Answers0