Javascript: Download data to file from content within the page

Simon picture Simon · Nov 15, 2010 · Viewed 47.5k times · Source

setting is the following: I have a homepage where I display a diagram that has been constructed using comma seperated values from within the page. I'd like to give users the possibility to download the data as cvs-file without contacting the server again. (as the data is already there) Is this somehow possible? I'd prefer a pure JavaScript solution.

So far I've discovered: http://pixelgraphics.us/downloadify/test.html but it involves flash which I'd like to avoid.

I can't imagine this question hasn't been asked before. I'm sorry to double post, but it seems I've used the wrong keywords or something - I haven't found a solution in these forums.

Answer

Zectbumo picture Zectbumo · Sep 16, 2011

Tested on Safari 5, Firefox 6, Opera 12, Chrome 26.

<a id='a'>Download CSV</a>
<script>
    var csv = 'a,b,c\n1,2,3\n';
    var a = document.getElementById('a');
    a.href='data:text/csv;base64,' + btoa(csv);
</script>

HTML5

<a id='a' download='Download.csv' type='text/csv'>Download CSV</a>
<script>
    var csv = 'a,b,c\n1,2,3\n';
    var data = new Blob([csv]);
    var a = document.getElementById('a');
    a.href = URL.createObjectURL(data);
</script>