Skip to content

Instantly share code, notes, and snippets.

@alpaca-tc
Created December 19, 2014 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alpaca-tc/a7507ae37a32412c3f16 to your computer and use it in GitHub Desktop.
Save alpaca-tc/a7507ae37a32412c3f16 to your computer and use it in GitHub Desktop.
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