2

I want to store a file to a local machine.

For HTML5, we can use cookies and local storage to store data to a local machine. Local storage uses key-value pairs (json) to store data. However, I want to save data in a different format, in XML for example.

On websites such as convertonlinefree.com, when a file has been converted, the file will automatically begin downloading.

So, I am considering a way to do this: When the user clicks a button, the XML file would automatically be downloaded. Is this possible? If so, how could I do that?

IronFlare
  • 2,287
  • 2
  • 17
  • 27
yongnan
  • 405
  • 7
  • 20
  • 1
    Is has been discussed here: http://stackoverflow.com/questions/19744155/writing-file-to-desktop-using-html5-filesystem-api – Christian Benseler Sep 02 '14 at 20:24
  • using http://danml.com/js/download.js, it's just download(strXmlData, "myxmlfile1.xml", "text/xml"); using dataURL alone might not trigger a download of XML since some browsers display the document... – dandavis Sep 02 '14 at 20:31
  • Thanks, I find this in discussion: http://stackoverflow.com/questions/19744155/writing-file-to-desktop-using-html5-filesystem-api – yongnan Sep 02 '14 at 20:32
  • http://pixelgraphics.us/downloadify/test.html is also a very good one – yongnan Sep 02 '14 at 20:33
  • @yongnan: yeah, downloadify is good for older browsers with flash. It is a bit stale though, and doesn't support newer devices/features/formats as well as my script (not that i'm biased). – dandavis Sep 02 '14 at 20:37
  • @dandavis thanks, It seems download.js is a good one(easy to use). – yongnan Sep 02 '14 at 20:40
  • It seems download.js have some problem in FireFox – yongnan Sep 23 '14 at 21:00

2 Answers2

2

You can create invisible element, such as a and emulate click on it, to download a file, check my codepen for demo.

The important part is this:

var text = xmlContent.value;
// Create element.
a = document.createElement('a');
// Attach href attribute with value of your file.
a.setAttribute("href", "data:application/xml;charset=utf-8," + text);
// HTML5 property, to force browser to download it.
a.setAttribute("download", "my.xml");
a.click();

Optionally you can replace application/xml part with intentionally incorrect MIME type, to force browser to download file instead of trying to display it.

David Sergey
  • 364
  • 1
  • 3
  • 18
0

What you'll want to use is Data_URI_scheme which basically means you have to base64 encode your file to download it.

So something like this should work:

window.location = 'data:application/xml;base64,'+ btoa("<xml>data in the file</xml>")
ShaneQful
  • 2,140
  • 1
  • 16
  • 22