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?

7
  • 1
    Is has been discussed here: stackoverflow.com/questions/19744155/… Commented Sep 2, 2014 at 20:24
  • using 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... Commented Sep 2, 2014 at 20:31
  • Thanks, I find this in discussion: stackoverflow.com/questions/19744155/… Commented Sep 2, 2014 at 20:32
  • pixelgraphics.us/downloadify/test.html is also a very good one Commented Sep 2, 2014 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). Commented Sep 2, 2014 at 20:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

you should make that a weirdo mime type to force a download, otherwise it might just show up...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.