Created
December 19, 2014 06:09
-
-
Save alpaca-tc/a7507ae37a32412c3f16 to your computer and use it in GitHub Desktop.
batchDownload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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