无法使用javascript下载大数据 [英] Unable to download large data using javascript

查看:54
本文介绍了无法使用javascript下载大数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有JSON对象形式的大数据.我已经使用JSON.stringify()将其转换为字符串.现在,我的用例是在文本文件中向用户提供这个大字符串.因此,为此,我编写了以下代码.

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代码

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

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

JavaScript代码

 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();
    });
 }; 

问题:当字符串长度较小时,我可以下载数据.但是当字符串长度变长(> 10 ^ 5)时,我的页面崩溃了.这是因为"encodeUriComponet(text)"无法编码较大数据.

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.

我还尝试了 window.open("data:attachment/txt," + encodeURIComponent(text)); 但是我的页面再次崩溃,是因为相同的原因,encodeURIComponet无法编码这么大的字符串.

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.

另一种方法:我也正在考虑使用HTML5 File write API将数据写入文件中,但是它仅在Chrome Web浏览器中受支持,但我需要使它至少适用于firefox和镀铬.

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.

我的目标是支持长度大约为10 ^ 6的字符串.谁能帮助我如何将大量数据下载/写入单个文件.

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.

推荐答案

通过OP :

我如下解决了.

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

注意:

  • 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

这篇关于无法使用javascript下载大数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆