我试图让用户使用Javascript和HTML5下载属性(http://caniuse.com/#feat=download)将一些数据下载为CSV(文本)文件。
数据以数组形式生成,然后添加到新的Blob对象中。
它在Chrome和Opera中完美运行,但在Firefox中根本不起作用。
原创示例我正在尝试复制:http://blog.eliacontini.info/post/79860720828/export-to-csv-using-javascript-the-download-attribute
小提琴:http://jsfiddle.net/8wos7cf8/5/
使用Javascript:
$('#downloadButton').click(function () {
// some data to export
var data = [{
"title": "Book title 1",
"author": "Name1 Surname1"
}, {
"title": "Book title 2",
"author": "Name2 Surname2"
}, {
"title": "Book title 3",
"author": "Name3 Surname3"
}, {
"title": "Book title 4",
"author": "Name4 Surname4"
}];
// prepare CSV data
var csvData = new Array();
csvData.push('"Book title","Author"');
data.forEach(function (item, index, array) {
csvData.push('"' + item.title + '","' + item.author + '"');
});
// download stuff
var fileName = "data.csv";
var buffer = csvData.join("\n");
var blob = new Blob([buffer], {
"type": "text/csv;charset=utf8;"
});
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
link.setAttribute("href", window.URL.createObjectURL(blob));
link.setAttribute("download", fileName);
link.click();
} else {
alert('CSV export only works in Chrome, Firefox, and Opera.');
}
});
HTML:
<div class="toggle-button" id="downloadButton"><span>Export to CSV</span></div>
当我添加警告时:
alert(window.URL.createObjectURL(blob));
我在Firefox中得到了这个结果:
...这导致Chrome / Opera:
因此出于某种原因,它似乎省略了Firefox中的URL路径。
答案 0 :(得分:74)
您可以尝试在触发点击之前将元素添加到DOM:
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
这在Firefox 34中对我有用
jsfiddle:http://jsfiddle.net/8wos7cf8/7/