Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and download an XML file on the fly using javascript?

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?

like image 567
Rahul Avatar asked Feb 28 '11 14:02

Rahul


2 Answers

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();
like image 171
Juan Avatar answered Oct 08 '22 02:10

Juan


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 :-)

like image 35
Mikel Avatar answered Oct 08 '22 02:10

Mikel