Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically create a document for download in Javascript?

I'm writing some Javascript code that generates an XML document in the client (via Google Earth plugin). I'd like the user to be able to click a button on the page and be prompted to save that XML to a new file. If I were generating the XML server-side this would be easy, just make the button open the link. But the XML is generated client-side.

I've come up with a couple of hacks that half-work, inspired in part by this StackOverflow question. But neither completely work. Here's a demo HTML with embedded code:

<html><head><script>
function getData() { return '<?xml version="1.0" encoding="UTF-8"?><doc>Hello</doc>'; }
function dlDataURI() {
  window.open("data:text/xml;charset=utf-8," + getData());
}
function dlWindow() {
  var w = window.open();
  w.document.open();
  w.document.write(getData());
  w.document.close();
}
</script><body>
<div onclick="dlDataURI()">Click for Data URL</div>
<div onclick="dlWindow()">Click for Window</div>
</body></html>

The dlDataURI() version works great in Firefox, poorly in Chrome (can't save), and not at all in IE. The Window() version works OK in Firefox and IE, and not well in Chrome (can't save, XML embedded inside HTML). Neither version ever prompts a user download, it always opens a new window trying to display the XML.

Is there a good way to do what I want in client side Javascript? I'd like this to work in today's browsers, ideally Firefox, MSIE 8, and Chrome.

Update with sample Downloadify code

window.onload = function() {
  Downloadify.create("dlify", {
    data: getData(),
    filename: "data.xml",
    swf: 'media/downloadify.swf',
    downloadImage: 'images/download.png',
    width: 100, height: 30});};
like image 562
Nelson Avatar asked Mar 22 '10 01:03

Nelson


1 Answers

The best I've seen as far is Downloadify by Doug Neiner, it requires Flash but works very well:

"A tiny JavaScript + Flash library that enables the generation and saving of files on the fly, in the browser, without server interaction."

Check this video.

like image 162
Christian C. Salvadó Avatar answered Sep 16 '22 18:09

Christian C. Salvadó