我正在尝试使用jszip插件从URL压缩两个文件,但是遇到了一些问题。我正在尝试从URL(目前在imgur链接上测试)中压缩两个文件,但是只有一个文件被压缩了。我不确定是否是我的foreach函数有问题?任何建议都将非常感谢,谢谢。
function urlToPromise(url)
{
return new Promise(function(resolve, reject)
{
JSZipUtils.getBinaryContent(url, function (err, data)
{
if(err)
{
reject(err);
} else {
resolve(data);
}
});
});
}
(function ()
{
var zip = new JSZip();
var count = 0;
var zipFilename = "instasamplePack.zip";
var urls = [
'https://i.imgur.com/blmxryl.png',
'https://i.imgur.com/Ww8tzqd.png'
];
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
// standard way
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
// old IE
el.attachEvent('on'+eventName, eventHandler);
}
}
// Blob
var blobLink = document.getElementById('kick');
if (JSZip.support.blob) {
function downloadWithBlob() {
urls.forEach(function(url){
var filename = "element" + count + ".png";
// loading a file and add it in a zip file
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
throw err; // or handle the error
}
zip.file(filename, urlToPromise(urls[count]), {binary:true});
count++;
if (count == urls.length) {
zip.generateAsync({type:'blob'}).then(function(content) {
saveAs(content, zipFilename);
});
}
});
});
}
bindEvent(blobLink, 'click', downloadWithBlob);
} else {
blobLink.innerHTML += " (not supported on this browser)";
}
})();