Download multiple file using data URI
by dshilkret
HTML
<a href="#" class="download-csv">Download all</a>
<!-- Some unuseful stuffs -->
<p>This example is related to <a href="http://diegolamonica.info/multiple-files-download-on-single-link-click/">Multiple files download on single link click</a>
</p>
<body>
</body>
CSS
/* Some unuseful stuffs */
html, body {
height: 100%;
overflow: hidden;
}
body {
background-image: url(http://diegolamonica.info/wp-content/uploads/2014/10/dlm-logo-small.png);
background-position: bottom right;
background-repeat: no-repeat;
}
* {
font-family: Arial;
}
p {
padding: 0.5em;
}
JavaScript
function downloadAll(files){
if(files.length == 0) return;
file = files.pop();
var theAnchor = $('<a />')
.attr('href', file[1])
.attr('download',file[0])
// Firefox does not fires click if the link is outside
// the DOM
.appendTo('body');
theAnchor[0].click();
theAnchor.remove();
downloadAll(files);
}
$('a.download-csv').on('click', function(){
downloadAll([
['file1.csv', 'data:text/csv;charset=utf8,'+
encodeURIComponent('my,csv,file\and,so,on')],
['file2.txt', 'data:text/plain;charset=utf8,'+
encodeURIComponent('this script can do what I need.')],
['file3.js', 'data:text/javascriptcharset=utf8,'+
encodeURIComponent('alert(\'You can donate me your house if you like this script :-) \')')]
]);
});