如果您正在尋找一個處理多個文件的代碼的好例子,see here。您可以然後view the source code。
此爲演示(只是略有修改)的主要來源:
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);
}
};
})();
用法: 假定<a id="downloadLink">Download</a>
元素存在提供下載,一旦準備就緒。
// 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);
您可以使用示例源代碼添加進度指示器。 希望這會有所幫助,關於這種方法的好處是zip模型很容易重用,如果你使它成爲自己的JS文件。
另一個想法:我想你使用的是getBase64Image
功能from here,如果是的話,你仍然遇到腐敗問題,也許嘗試修改迴歸簡單return dataURL;
並註釋掉.replace(...
,作爲Data64URIReader
可能期望前綴。
THX! :)這似乎工作。我有最後一個問題,只有最後一張圖片在zip中保存了好幾次。我認爲它來自模型函數。我正在研究它。 –
幾分鐘前,我對代碼進行了更改,您可能還沒有。在圖像加載器中確保URL的'var'正面或'onload'函數不會正確拾取變量。 – Scott
讓我知道你是否需要任何進一步的幫助。 – Scott