2017-05-21 75 views
0

JavaScriptとJSZipを使用して、いくつかの画像ファイルをダウンロードして1つのzipファイルに保存しようとしています。しかし、これは空のzipファイルを返しています。私は間違って何をしていますか?私はJSZipとJSZipとJS-Zip Utilsで画像をダウンロードしてZipとしてダウンロード

function createZip() { 

//Create zip file object 
var zip = new JSZip(); 

//Add folders 

//Add files 
JSZipUtils.getBinaryContent("icons/8_Bit_Character.png", function (err, data) { 
    if(err) { 
     throw err; // or handle the error 
    } 
    zip.file("picture.png", data, {binary:true}); 
}); 

JSZipUtils.getBinaryContent("icons/16_Bit_Character.png", function (err, data) { 
    if(err) { 
     throw err; // or handle the error 
    } 
    zip.file("picture2.png", data, {binary:true}); 
}); 

//Compile all the data into memory. 
var base64 = null; 
if (JSZip.support.uint8array) { 
    promise = zip.generateAsync({type : "uint8array"}); 
} else { 
    promise = zip.generateAsync({type : "string"}); 
} 

//Generate the zip file and download it. 
zip.generateAsync({type:"base64"}).then(function (base64) { 
    location.href="data:application/zip;base64," + base64; 
}); 

} 

答えて

1

JSZipUtils.getBinaryContent内部関数が非同期的に起こっているJSZip-utilsのを使用しています。 zip.generateAsyncに電話すると、まだzip.file("picture.png", data, {binary:true});は起きていません。ここで

は私の例です:

var count = 0; 
....... 
JSZipUtils.getBinaryContent(imageUrl, function (err, data) { 
      if (err) { 
       // throw err; // or handle the error 
       console.log(err); 
      } 
      else { 
       zip.file(fileName, data, { binary: true }); 
       count++;      
       if (count == selectedImages.length) {       
        zip.generateAsync({ type: "blob" }).then(function (base64) {        
        // window.location.replace("data:application/zip;base64," + base64); 

         saveAs(base64, `archive.zip`); 

         console.log("inner"); 
        }); 
       } 
      } 
     }); 
0

documentationMini app : downloader例から機能を使用してみてください。これによりコンテンツが取得され、そのコンテンツ/画像の約束が返されます。

function urlToPromise(url) { 
return new Promise(function(resolve, reject) { 
    JSZipUtils.getBinaryContent(url, function (err, data) { 
     if(err) { 
      reject(err); 
     } else { 
      resolve(data); 
     } 
    }); 
    }); 
} 

zip.file(filename, urlToPromise(url), {binary:true}); 
関連する問題