javascript 跨浏览器另存为.txt
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6464828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross-browser Save As .txt
提问by Christophe
Is there a JavaScript library that allows to save strings as txt files, and works cross-browser?
是否有允许将字符串保存为 txt 文件并跨浏览器工作的 JavaScript 库?
In the past, I have been using Downloadify, but I am looking at another option for a couple reasons:
过去,我一直在使用 Downloadify,但出于以下几个原因,我正在寻找另一种选择:
- I hope to find a pure JavaScript solution, without the need for Flash
- it seems that Downloadify is not updated anymore (no update in the past 18 months)
- I am experiencing an issue with Downloadify in IE 9, where strings are cut off
- 我希望找到一个纯 JavaScript 的解决方案,不需要 Flash
- Downloadify 似乎不再更新(过去 18 个月没有更新)
- 我在 IE 9 中遇到 Downloadify 问题,其中字符串被切断
回答by Viacheslav Dobromyslov
Here iswhat you need. But it's not cross-browser yet. Works in Google Chrome.
这是你需要的。但它还不是跨浏览器。在谷歌浏览器中工作。
<a download="MyFile.txt"
href="your-data-uri-here"
draggable="true"
class="dragout"
>Download ready</a>
Also Wikipedia has a good article about Data URI
维基百科也有一篇关于数据 URI的好文章
回答by Wladimir Palant
As far as I know, the only way is to use data: URLs to force a download:
据我所知,唯一的方法是使用 data: URL 强制下载:
var data = "This is a test";
window.location.href = "data:application/x-download;charset=utf-8," + encodeURIComponent(data);
Two catches here:
这里有两个问题:
- It won't work in MSIE because its support of data: URLs is very limited (supposedly for security reasons). So you will still need Downloadify there.
- You cannot specify a file name, the suggested file name will depend on the browser used. And file type will be "unknown" (you cannot use a known MIME type because the browser won't offer to download the file then).
- 它在 MSIE 中不起作用,因为它对 data: URLs 的支持非常有限(据说是出于安全原因)。所以你仍然需要在那里下载。
- 您不能指定文件名,建议的文件名将取决于所使用的浏览器。并且文件类型将为“未知”(您不能使用已知的 MIME 类型,因为浏览器不会提供下载文件)。
Bonus reading: there was a W3.org discussion in February 2010 on fixing the second problem: http://lists.w3.org/Archives/Public/uri/2010Feb/thread.html#msg58. However, this doesn't seem to have made it into any specification so far, let alone browser implementations.
额外阅读:2010 年 2 月 W3.org 讨论了解决第二个问题:http: //lists.w3.org/Archives/Public/uri/2010Feb/thread.html#msg58。然而,到目前为止,这似乎还没有成为任何规范,更不用说浏览器实现了。