我需要将多个图像保存到文件系统。但是在文件系统中只输入了最后一张图像。我怎么解决这个问题?
这是我的代码:
// Loop through each image and to create image blob
for(var slide in slides)
{
var image = "http://localhost:5441"+slides[slide].background.src;
xhrDownloadImage(image, function (imageAsBlob) {
});
}
}
// Function to create blob
var ids = [];
var xhrDownloadImage = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onerror = function(e){console.log("Error: " + e)};
xhr.onabort = function(e){console.log("Abort: " + e)};
xhr.onload = function () {
console.log("onload");
var result;
if (xhr.status === 200) {
// image as blob
result = xhr.response;
ids.push(result);
console.log(result);
} else {
result = null;
}
callback(result);
};
console.log(xhr.send());
};
// Now ids array has all image blobs
//Following function is to write image blobs in ids to file systems
function writedata(){
console.log(ids);
for(var i in ids)
{
alert("image"+i+".png");
setTimeout(function () {
(function () {
fs.root.getFile("image"+i+".png", { create: true }, function (fileEntry) {
alert("fileimage"+n+".png");
console.log(fileEntry);
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
console.log("image successfully written to filesystem.");
};
var blob = new Blob([ids[i]]);
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
})(i)
}, i * 1000);
}
}
答案 0 :(得分:0)
我开始工作了......
将writedata fn更改为
function writedata() {
console.log(filesystem);
console.log(ids);
for (var i = 0; i < ids.images.length; i++) {
var n = -1;
setTimeout(function() {
(function() {
filesystem.root.getFile(ids.images[n + 1].name, {
create: true
}, function(fileEntry) {
console.log(fileEntry);
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log("image successfully written to filesystem.");
};
var blob = new Blob([ids.images[n].blob]); // instead i (ie looping variable), n is used which increments only after writing each file to file system
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
n = n + 1;
})(i)
}, i * 1000);
}
}