我收到了以下需求:
网页上有一个链接。当用户点击这个链接时,它应该即时创建一个文件,并弹出下载框。如何使用JavaScript实现这一功能?
我收到了以下需求:
网页上有一个链接。当用户点击这个链接时,它应该即时创建一个文件,并弹出下载框。如何使用JavaScript实现这一功能?
您可以像此示例中所示使用blob。
您可以使用以下代码的JavaScript函数:
var xmltext = "<sometag><someothertag></someothertag></sometag>";
var filename = "file.xml";
var pom = document.createElement('a');
var bb = new Blob([xmltext], {type: 'text/plain'});
pom.setAttribute('href', window.URL.createObjectURL(bb));
pom.setAttribute('download', filename);
pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':');
pom.draggable = true;
pom.classList.add('dragout');
pom.click();
pom
? - Kubuntuer82尝试了Andreas的建议后,我想再加一些东西:
脚本:
function createAndOpenFile(){
var stupidExample = '<?xml version="1.0" encoding="utf-8"?><aTag>something</aTag>';
document.open('data:Application/octet-stream,' + encodeURIComponent(stupidExample));
}
你有一个像这样的链接,注意新的 download 属性,使用它你可以设置文件名。
<a href="#" onclick="createAndOpenFile()" download="file.xml">Donwload</a>
它至少可在Chrome 27和Firefox 21中使用。
欢迎改进 :-)
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;
}
decodeRequest(textToDecode) {
var decodedString = atob(textToDecode);
var fileName = "fileName1"+'_RQ';
var fileType = '.xml';
var blob = new Blob([decodedString], { type: fileType });
var a = document.createElement('a');
a.download = fileName;
a.href = URL.createObjectURL(blob);
a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500);
}