前端JS_實現打包下載OSS檔案
阿新 • • 發佈:2021-08-04
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 匯入需要使用的模組 --> <script type="text/javascript"src="./js_zip/jszip.min.js"></script> <script type="text/javascript" src="./js_zip/FileSaver.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script> <title>Document</title> </head> <body> <script>var zip = new JSZip(); // 檔案列表 var baseList = ["http://photolife-imag...._photo/_DSC3087.jpg", "http://photolife....347.jpg"] function getBase64(imgUrl) { return new Promise(resolve => { window.URL = window.URL || window.webkitURL;var xhr = new XMLHttpRequest(); xhr.open("get", imgUrl, true); // 至關重要 xhr.responseType = "blob"; xhr.onload = function () { if (this.status == 200) { //得到一個blob物件 var blob = this.response; // 至關重要 let oFileReader = new FileReader(); oFileReader.onloadend = function (e) { let base64 = e.target.result; // 返回解碼後的base64 resolve(base64) }; oFileReader.readAsDataURL(blob); } } xhr.send(); }) } async function wdc () { var vars = {} for(var i=0;i<baseList.length;i++){ // 動態生成變數,建立資料夾 let varName = "wdc_" + i; vars[varName] = zip.folder("wdc_" + i); vars[varName].file("hello.txt", "Hello World\n"); // 呼叫解碼函式 let base_photo = await getBase64(baseList[i]) // 將檔案寫入到壓縮檔案 vars[varName].file(i + ".jpg", base_photo.replace(/^data:image\/\w+;base64,/, ""), {base64: true}); } zip.generateAsync({type:"blob"}).then(function(content) { // see FileSaver.js saveAs(content, "aaaa.zip"); }); } wdc() </script> </body> </html>