2013-07-07 67 views
6

Tôi đang sử dụng thư viện javascript zip.js. Tôi đã tìm kiếm tất cả các xung quanh tôi, tôi không thể tìm thấy một ví dụ mà nhiều hơn một tập tin được thêm vào zip.Cách thêm nhiều tệp vào một tệp zip bằng zip.js?

Đây là mã của tôi, nhưng mã này tạo ra một mã zip "bị hỏng".

var len = results.rows.length, i; 
var k=1; 
zip.createWriter(new zip.BlobWriter(), function(writer) { 
    for (i = 0; i < len; i++){ 
     // get the image url from a sqlite request 
     url = results.rows.item(i).url; 


     var img = new Image(); 
     img.onload = function() { 
      var a = document.createElement('a'); 
      a.href = this.src; 
      var filename= a.pathname.split('/').pop(); // filename.php 
      timest = new Date().getTime(); 
      // use a TextReader to read the String to add 

       writer.add(timest+".jpg", new zip.Data64URIReader(getBase64Image(img)), function() { 
       // onsuccess callback 
        k++; 
        if(k==len){ 
         setTimeout(function(){ 
         writer.close(function(blob) { 

          // blob contains the zip file as a Blob object 
          $('#test').attr("href", window.URL.createObjectURL(blob)); 
          $('#test').attr("download", "woeii.zip"); 

         }); 
         },1000); 
        } 
       }, function(currentIndex, totalIndex) { 
       // onprogress callback 
       }); 



     }; 
     img.src = url; 
    } 
}); 

Bất kỳ ý tưởng nào để nó hoạt động? :)

Trả lời

6

Nếu bạn đang tìm kiếm một ví dụ điển hình về mã xử lý nhiều tệp, see here. Sau đó, bạn có thể view the source code.

Đây là nguồn gốc chính của bản demo (sửa đổi chỉ một chút):

var obj = this; 
var model = (function() { 
    var zipFileEntry, zipWriter, writer, creationMethod, URL = obj.webkitURL || obj.mozURL || obj.URL; 

    return { 
     setCreationMethod : function(method) { 
      creationMethod = method; 
     }, 
     addFiles : function addFiles(files, oninit, onadd, onprogress, onend) { 
      var addIndex = 0; 

      function nextFile() { 
       var file = files[addIndex]; 
       onadd(file); 
       // Modified here to use the Data64URIReader instead of BlobReader 
       zipWriter.add(file.name, new zip.Data64URIReader(file.data), function() { 
        addIndex++; 
        if (addIndex < files.length) 
         nextFile(); 
        else 
         onend(); 
       }, onprogress); 
      } 

      function createZipWriter() { 
       zip.createWriter(writer, function(writer) { 
        zipWriter = writer; 
        oninit(); 
        nextFile(); 
       }, onerror); 
      } 

      if (zipWriter) 
       nextFile(); 
      else if (creationMethod == "Blob") { 
       writer = new zip.BlobWriter(); 
       createZipWriter(); 
      } else { 
       createTempFile(function(fileEntry) { 
        zipFileEntry = fileEntry; 
        writer = new zip.FileWriter(zipFileEntry); 
        createZipWriter(); 
       }); 
      } 
     }, 
     getBlobURL : function(callback) { 
      zipWriter.close(function(blob) { 
       var blobURL = creationMethod == "Blob" ? URL.createObjectURL(blob) : zipFileEntry.toURL(); 
       callback(blobURL); 
       zipWriter = null; 
      }); 
     }, 
     getBlob : function(callback) { 
      zipWriter.close(callback); 
     } 
    }; 
})(); 

Cách sử dụng: Giả một yếu tố <a id="downloadLink">Download</a> tồn tại để cung cấp việc tải xuống một lần đã sẵn sàng.

// Prepare your images 
var files = []; 
for (i = 0; i < len; i++) { 

    // Get the image URL from a SQLite request 
    var url = results.rows.item(i).url; 

    (function(url){ 
     var img = new Image(); 
     img.onload = function() { 
      // Add to file array [{name, data}] 
      var a = document.createElement('a'); 
      a.href = this.src; 
      var filename= a.pathname.split('/').pop(); 

      console.log("Loaded file " + filename); 
      files.push({name: filename, data: getBase64Image(img) }); 
     } 
     img.src = url; 
    })(url); 
} 

// Wait for the image to load 
var check = setInterval(function(){ 
    if(files.length==images.length) { 
     clearInterval(check); 

     // Set the mode 
     model.setCreationMethod("Blob"); 

     // Add the files to the zip 
     model.addFiles(files, 
      function() { 
       // Initialise Method 
       console.log("Initialise"); 
      }, function(file) { 
       // OnAdd 
       console.log("Added file"); 
      }, function(current, total) { 
       // OnProgress 
       console.log("%s %s", current, total); 
      }, function() { 
       // OnEnd 
       // The zip is ready prepare download link 
       // <a id="downloadLink" href="blob:url">Download Zip</a> 
       model.getBlobURL(function(url) { 
        document.getElementById("downloadLink").href = url; 
        document.getElementById("downloadLink").style.display = "block"; 
        document.getElementById("downloadLink").download = "filename.zip"; 
       }); 
      }); 

    } 
}, 500); 

Bạn có thể sử dụng mã nguồn ví dụ để thêm các chỉ báo tiến trình. Hy vọng điều này sẽ giúp, những điều tốt đẹp về phương pháp này là mô hình zip là dễ dàng tái sử dụng nếu bạn làm cho nó là tập tin JS của riêng.


Một suy nghĩ: Tôi đoán bạn đang sử dụng getBase64Image chức năng from here, nếu như vậy và bạn vẫn gặp vấn đề tham nhũng, có lẽ cố gắng sửa đổi lại chỉ đơn giản là return dataURL; và xóa bỏ .replace(..., như Data64URIReader có thể mong đợi các tiền tố .

+0

Thx! :) Điều này dường như làm việc. Tôi có một vấn đề cuối cùng, chỉ có hình ảnh cuối cùng được lưu nhiều lần trong zip. Tôi nghĩ nó đến từ chức năng mô hình. Tôi đang nhìn vào nó. –

+0

Tôi đã thực hiện thay đổi đối với mã một vài phút trước đây mà bạn có thể chưa nhận được. Trong trình tải hình ảnh đảm bảo có 'var' infront của URL hoặc hàm' onload' sẽ không nhận biến đúng cách. – Scott

+0

Hãy cho tôi biết nếu bạn cần thêm trợ giúp. – Scott

2

Đây là phiên bản rút gọn của that demo chỉ sử dụng bộ nhớ RAM. Nó giả định rằng zip.js, z-worker.js và deflate.js từ cài đặt zip.js nằm trong cùng thư mục với hai tệp bên dưới, cùng với FileSaver.js.

Lưu ý: Đây không phải là mã sản phẩm sẵn sàng! Đó là một bản demo xương trần mà tôi đã tạo ra để tôi có thể tìm ra những gì đang diễn ra. Nếu bạn tạo và lưu mã zip theo chương trình, bạn có thể cần phải triển khai một trình lặp tiếp theo() iterator giống như trình ở trên để ngăn chặn tình trạng chủng tộc điền vào tệp zip với các tệp rỗng. (Xem https://stackoverflow.com/a/29738675/738675 cho một ví dụ về điều này.)

demo.html:

<li> 
    add files into the zip 
    <input type="file" multiple id="file-input" onchange="addFiles(this.files)"> 
</li> 
<li> 
    download the zip file 
    <a href="#" onclick="saveZip()">Download</a> 
</li> 

<script type="text/javascript" src="zip.js"></script> 
<script type="text/javascript" src="demo.js"></script> 
<script type="text/javascript" src="FileSaver.js"></script> 

demo.js:

var zipWriter; 

function addFiles(files) { 
    writer = new zip.BlobWriter(); 
    zip.createWriter(writer, function(writer) { 
     zipWriter = writer; 
     for (var f = 0; f < files.length; f++) { 
      zipWriter.add(files[f].name, 
      new zip.BlobReader(files[f]), function() {}); 
     } 
    }); 
} 

function saveZip() { 
    zipWriter.close(function(blob) { 
     saveAs(blob, "Example.zip"); // uses FileSaver.js 
     document.getElementById("file-input").value = null; // reset input file list 
     zipWriter = null; 
    }); 
} 
Các vấn đề liên quan