问题描述
我想创建使用JavaScript的文本文件,我知道这是可能通过使用ActiveX对象,但它只能在IE浏览器上运行良好。
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的Safari浏览器上生成一个文本文件?
My requirement is to generate a text file using JavaScript for a Safari browsers?
谁能帮我在这方面?
推荐答案
另一种方式来做到这将是使用的和<$c$c>URL.createObjectURL$c$c>.所有最新的浏览器包括Safari 6+支持他们。
Another way to do it would be to use a Blob
and URL.createObjectURL
. All recent browsers including Safari 6+ support them.
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 example that uses this technique to save arbitrary text from a textarea
.
需要注意的例子另一件事是,我使用的 下载
属性一>下载链接。不幸的是,Safari浏览器目前不支持它。在做浏览器不过,该文件将被自动点击,而不是在浏览器中打开文件时,下载。此外,由于我设置了下载
属性信息.txt
该文件将使用该名称,而不是随机下载通过名称 createObjectURL
生成的。
Another thing to note about the example is that I used the download
attribute on 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
.
这篇关于在JavaScript中创建的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!