用 JavaScript 创建文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8178825/
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
Create text file in JavaScript
提问by nagendra
I am trying to create a text file using JavaScript, I know it is possible by using ActiveX object, but it runs well only on IE browsers.
我正在尝试使用 JavaScript 创建一个文本文件,我知道使用 ActiveX 对象是可能的,但它只能在 IE 浏览器上运行良好。
My requirement is to generate a text file using JavaScript for a Safari browsers?
我的要求是使用 JavaScript 为 Safari 浏览器生成文本文件?
Can anyone help me in this regard?
任何人都可以在这方面帮助我吗?
回答by Useless Code
Another way to do it would be to use a Blob
and URL.createObjectURL
. All recent browsers including Safari 6+ support them.
另一种方法是使用 a Blob
and URL.createObjectURL
。所有最近的浏览器,包括 Safari 6+ 都支持它们。
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an examplethat uses this technique to save arbitrary text from a textarea
.
这里有一个例子,使用这种技术来从保存任意文本textarea
。
Another thing to note about the example is that I used the download
attributeon the download link. Unfortunately, Safari does not currently support it. However in browsers that do, the file will automatically be downloaded when clicked instead of opening the file in the browser. Also, since I set the download
attribute to info.txt
the file will be downloaded with that name instead of the random name generated by createObjectURL
.
关于该示例的另一件事是我在下载链接上使用了该download
属性。不幸的是,Safari 目前不支持它。然而,在浏览器中,点击时会自动下载文件,而不是在浏览器中打开文件。此外,由于我将download
属性设置info.txt
为文件,将使用该名称而不是由createObjectURL
.
回答by Amit
In JavaScript, you can use the following line to ask the user for saving a text file:
在 JavaScript 中,您可以使用以下行来要求用户保存文本文件:
window.open("data:text/json;charset=utf-8," + escape("Ur String Object goes here"));
I tested this in some popular browsers some time back but please check if it works in Safari or not.
一段时间前,我在一些流行的浏览器中对此进行了测试,但请检查它是否适用于 Safari。
回答by Sarfraz
but my requirement is to generate a text file using javascript for a safari browser
但我的要求是使用 javascript 为 safari 浏览器生成一个文本文件
That's not possible with vanilla JavaScript due to security restrictions. You can however use server-side JavaScript such as Node.JS or Ajax or some other server-side technology.
由于安全限制,vanilla JavaScript 无法做到这一点。但是,您可以使用服务器端 JavaScript,例如 Node.JS 或 Ajax 或其他一些服务器端技术。