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 using java script?
You can use blobs as shown in this example.
You can have a JavaScript function with the following code:
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();
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With