I got a requirement as following:
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 u
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);
}
After try what Andreas said I will add something:
Script:
function createAndOpenFile(){
var stupidExample = '<?xml version="1.0" encoding="utf-8"?><aTag>something</aTag>';
document.open('data:Application/octet-stream,' + encodeURIComponent(stupidExample));
}
You have a link like this, note the new download atribute, with it you put the file name.
<a href="#" onclick="createAndOpenFile()" download="file.xml">Donwload</a>
It works at least in Chrome 27 and Firefox 21.
Improved are welcome :-)
You can use blobs as shown in this example http://html5-demos.appspot.com/static/a.download.html
You can have a javacript function with the following code
var xmltext = "<sometag><someothertag></someothertag></sometag>";
var pom = document.createElement('a');
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();
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;
}
if you need support for all browsers, see how it is implemented in http://www.tiddlywiki.com
EDIT: 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
You could create a data-URI. Most modern browsers should be able to understand it. See http://en.wikipedia.org/wiki/Data_URI_scheme