Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
batchDownload
// Required plugins
// - https://github.com/eligrey/FileSaver.js
// - https://github.com/Stuk/jszip
// feature-detect against window.FormData, window.Blob and window.ArrayBuffer
var isSupported = !!(window.FormData && window.Blob && window.ArrayBuffer);
var downloadFile = function (url) {
var xhr = new XMLHttpRequest(),
deferred = new $.Deferred();
xhr.addEventListener('load', function() {
deferred.resolve(xhr);
});
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.send();
return deferred.promise()
}
var batchDownload = function(urlList) {
var zip = new JSZip(),
deferreds = [];
for (var i = 0; i < urlList.length; i += 1) {
var deferred = (function(index) {
return downloadFile(urlList[index]).done(function(xhr) {
filename = 'file' + index + '.png'
zip.file(filename, xhr.response)
})
})(i)
deferreds.push(deferred);
}
$.when.apply($, deferreds).done(function() {
saveAs(zip.generate({ type: 'blob' }), 'example.zip');
});
};
$(function() {
$('#batch_download').on('click', function(event) {
event.preventDefault();
batchDownload('http://...', 'http://...');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment