[英]How can i generate a file and offer it for download in plain javascript?
I would like to generate a text file in the javascript dynamicly, then offer this for download.我想在 javascript 中动态生成一个文本文件,然后提供下载。 Currently I can get this working to a degree with either of the following solutions:目前,我可以通过以下任一解决方案将其工作到一定程度:
content = "abc123";
document.location = "data:text/octet-stream," + encodeURIComponent(content);
OR或者
content = "abc123";
var bb = new BlobBuilder();
bb.append(content);
var blob = bb.getBlob();
blob = blob.slice(0, blob.size, 'text/octet-stream');
var fr = new FileReader();
fr.onload = function() {document.location = this.result;}
fr.readAsDataURL(blob);
However, Both of these solutions, when the download box appears, will only offer a default filename of 'download' in the save as dialogue.但是,当下载框出现时,这两种解决方案都只会在另存为对话框中提供默认文件名“下载”。
My question is basically, how can I change this to a specific filename for example 'readme.txt' or 'scene.obj'我的问题基本上是,如何将其更改为特定的文件名,例如“readme.txt”或“scene.obj”
Also note the data type was previously 'text/plain' however if this is used, the document switches to the new text document instead of offering it for download (as text/octet-stream seems to do).另请注意,数据类型以前是“文本/纯文本”,但是如果使用它,文档将切换到新的文本文档,而不是提供下载(就像 text/octet-stream 似乎一样)。
I do not want a flash solution, javascript/html5 only suggestions please.我不想要 flash 解决方案,请仅提供 javascript/html5 建议。
Cheers, Josh干杯,乔什
For that, you will have to use FileSaver from FileAPI: Writer specification.为此,您必须使用 FileAPI: Writer 规范中的FileSaver 。 For now, it's only a draft, and according to mailing list answer it isn't yet implemented in browsers.目前,它只是一个草稿,根据邮件列表的回答,它还没有在浏览器中实现。
You can watch for example on a chromium issue to get up-to-date information about the implementation progress例如,您可以观看铬问题以获取有关实施进度的最新信息
UPD 02.08.2013: I have since found a project that provides FileSaver interface using neat tricks UPD 02.08.2013:我发现了一个使用巧妙技巧提供 FileSaver 界面的项目
I think you should check: jQuery Table to CSV export我认为您应该检查: jQuery Table to CSV export
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.