Generating a downloadable file from JavaScript

Recently, a friend asked me if I could help him with a very simple task: have a dialog with an input text field where he could paste some csv lines and press a “save” button that would reformat the csv and write it to a file.

I thought that the input text field and the reformatting could be done very easily with a web page and a few JavaScript lines, but I was afraid I wouldn’t be able to save anything back to the disk without having some sort of server to serve the final result.

I’m so very glad I was wrong! It turns out that it is possible to generate a file in JavaScript. In fact, it’s possible with pure html. All you have to do is use an anchor tag and set the proper “href” property. Here is an example.

<a href="data:application/csv,Col1%2CCol2%2CCol3" download="file.csv">save</a>

“data:application/csv” does it. I know there are other possible parameters but I haven’t tried them. After there is a comma followed by an uri encoded string to “download” to a file. Using JavaScript you can simply use the “encodeURIComponent” function to encode any string you want.

Here is a short live demo.


Source

<label>1 - Text to save to file: </label><input id="demoInputField" type="text" value="foo bar" />
<label>2 - Hit the save link: <a id="demoAnchor" href="#">Save</a>
jQuery(function(){
    jQuery("#demoAnchor").click(function(){
        jQuery(this).attr({
            "href" : "data:application/csv," + encodeURIComponent(jQuery("#demoInputField").val())
        });
    });
});

Boringly simple eh? And I was afraid I would need to code something heavy in Java or C#. This solution is super lightweight and portable. W00t!

Reference: StackOverflow

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.