本地文件下载有很多内容

时间:2017-05-23 18:56:54

标签: javascript html5 reactjs

我使用本地浏览器内数据库来存储数据。但是,我想让用户能够将该数据导出为CSV。

谷歌搜索时我找到了带有数据网址的解决方案 - 用数据准备网址。然而,在我的情况下,每次呈现页面(链接)时生成的是> 1MB的数据。是否有任何替代解决方案可以让我从JavaScript生成文件下载,但不要求我提前准备内容 - 仅当用户实际点击链接时?

如果重要的是我使用React来构建我的应用程序..

1 个答案:

答案 0 :(得分:13)

尝试blob。

(不,不是那种)

demo

var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
open(url);

需要将JSON转换为CSV吗?

demo

https://stackoverflow.com/a/14966131/6560716

var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;
}); 
var blob = new Blob([csvContent], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
open(url);

需要有文件名吗?

demo

var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();

文件名和JSON?

demo

var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;
}); 
var blob = new Blob([csvContent], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();