Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to download large data using javascript

I have a large data in form of JSON object in the javascript. I have converted it into the string using JSON.stringify(). Now my use case is to provide this large string in a text file to the user. So for this i have written below code.

HTML code

  <button id='text_feed' type="submit">Generate ION Feed</button>

  <a href="data:attachment/txt" id="textLink" download="feed.txt"></a>

Javascript code

 var text = //huge string  

 $("#text_feed").click(function() {
        _generateFeed(text);
 });

 var _generateFeed = function(text) {
    //some code here
    $("#textLink").attr("href",
                          "data:attachment/txt," + encodeURIComponent(text))  [0].click();
    });
 }; 

Problem: When the string length is small , i am able to download the data . But when the string length goes higher (> 10^5) , my page crashes. This occurred because "encodeUriComponet(text)" is not able to encode large data.

I also tried window.open("data:attachment/txt," + encodeURIComponent(text)); But again my page got crashed because of the same reason that encodeURIComponet was unable to encode such a large string.

Another approach: I was also thinking of writing the data into a file using HTML5 File write API , but it has support only in Chrome web browser , but i need to make this work for atleast firefox and chrome both.

Use Case I don't want to do multiple downloads by breaking the data, as i need to have data in a single file in the end.

And my target is to support string of aprroximately 10^6 length. Can anyone help me how to download/write this amount of data into a single file.

like image 807
ankur37 Avatar asked May 11 '15 12:05

ankur37


1 Answers

From the OP:

I solved it as below.

var _generateFeed = function(text) {
    /*some code here*/
    var url = URL.createObjectURL( new Blob( [text], {type:'text/plain'} ) );
    $("#textLink").attr("href",url)[0].click();
}; 

Notes:

  • URL.createObjectURL() is compatible with modern browsers and IE10+, but it is an unstable, experimental technology.
  • Objects created using URL.createObjectURL() "must be released by calling URL.revokeObjectURL() when you no longer need them." - MDN
like image 166
3 revs Avatar answered Oct 20 '22 18:10

3 revs