简体   繁体   English

CSV下载文件名

[英]CSV download File Name

I am trying to download a CSV file from json data stored in a variable. 我正在尝试从存储在变量中的json数据下载CSV文件。

The issue is that I am not able to set the name of the downloaded file. 问题是我无法设置下载文件的名称。

Here is the code... 这是代码...

$('#downloadCSV').click(function () {
    var exportData = 'data:attachment/csv;charset=utf-8,';
    exportData += 'nodeid,value\n1,212\n';
    var newWindow = window.open(encodeURI(exportData));
    return false;
});

I have already tried to add the HTML5 download attr: 我已经尝试添加HTML5下载属性:

<a id="downloadCSV" download="data.csv" href="#">Download CSV</a>

I have already tried the solutions provided by others and nothing is working with the current browsers ... 我已经尝试了其他人提供的解决方案,但当前的浏览器无法正常工作...

I find the FileSaver library a really useful cross-browser solution for saving files from JavaScript. 我发现FileSaver库是一个非常有用的跨浏览器解决方案,用于从JavaScript保存文件。 Their documentation provides a compatibility table which will show you which browsers support file names. 他们的文档提供了一个兼容性表,该表将向您显示哪些浏览器支持文件名。

BTW the download attribute on the <a> tag is an HTML5 feature which would apply if you were linking to a file's URL directly with the href . 顺便说一句, <a>标记上的download属性是HTML5功能,如果您直接使用href链接到文件的URL,则该功能将适用。 As you are catching the click event using JavaScript, and then returning false, this will not be doing anything. 当您使用JavaScript捕获click事件,然后返回false时,将不会执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM