如何使用javascript动态创建和下载XML文件? [英] How to create and download an XML file on the fly using javascript?
问题描述
我有如下要求:
网页上有一个链接.当用户单击链接时,它应立即创建一个文件,并弹出一个下载框.如何使用Java脚本做到这一点?
There is a link on a web page. As user clicks on link it should create a file on the fly and a download box pops up. How to do it using java script?
推荐答案
如果用户信任您,则可以直接在其文件系统中创建XML文件. Mozilla Firefox的示例代码:
If the user trusts you, you can can create XML file directly in his filesystem. Example code for Mozilla Firefox:
function mozillaSaveFile(filePath,content)
{
if(window.Components) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(filePath);
if(!file.exists())
file.create(0,0664);
var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
out.init(file,0x20|0x02,00004,null);
out.write(content,content.length);
out.flush();
out.close();
return true;
} catch(ex) {
return false;
}
}
return null;
}
如果您需要对所有浏览器的支持,请在 http://www.tiddlywiki.com
if you need support for all browsers, see how it is implemented in http://www.tiddlywiki.com
这不适用于 Firefox 17 + ,因为更改特权被认为是不安全的并已被删除.请参阅此处以了解更多详细信息: https://bugzilla.mozilla.org/show_bug.cgi ?id = 546848#c57
This doesn't work for Firefox 17+ because changing privileges was deemed unsafe and removed. see here for more details: https://bugzilla.mozilla.org/show_bug.cgi?id=546848#c57
这篇关于如何使用javascript动态创建和下载XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!