我已经使用phonegap fileTransfer方法循环遍历数组以将图像上传到我的服务器,但无论出于何种原因,我都无法弄清楚如何在所有文件上传完成后触发事件。似乎我的迭代计数器(在下面的示例中为i)立即达到最大限制(results.length),并且事件触发每次迭代。你可以看到我已经设置了当最后一个图像上传到100%并且迭代到达数组末尾时发生事件的条件。但是,警报事件将在每个图像上传后发生,而不是在结束时上传一次。
我做错了什么?
以下是代码:
$("#btn_upload").click(
function() {
window.imagePicker.getPictures(function(results) {
$("#uploadingContainer").css("display", "block");
for (var i = 0; i < results.length; i++) {
var serverUrl = 'http://www.example.com/myuploadhandler.php';
var imageURI = results[i];
var options = new FileUploadOptions();
var params = {};
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var ft = new FileTransfer();
var statusDom = document.querySelector('#uploadingProgressText');
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = parseInt(
(progressEvent.loaded / progressEvent.total) * 100, 10);
//hack to get the apparent hangup at 99% to 100%
if (perc >= 99) {
perc = 100;
}
statusDom.innerHTML = perc + "% uploaded...";
if (perc == 100 && i == results.length-1) {
alert("Complete"); // <--- this fires every iteration of the array instead of only after the last iteration. How did i get to be results.length already?
/* This is the event I eventually want to happen
* $(':mobile-pagecontainer').pagecontainer(
* 'change', '#thispage', {
* allowSamePageTransition : true, transition :
* 'pop', changeHash : false, reverse : false,
* showLoadMsg : false });
*/
}
} else {
if (statusDom.innerHTML == "") {
statusDom.innerHTML = "Loading";
} else {
statusDom.innerHTML += ".";
}
}
};
ft.upload(imageURI, serverUrl, function(r) {
// console.log("Upload successful: "
// + r.bytesSent + " bytes uploaded.");
}, function(error) {
console.log("Upload failed: Code = " + error.code);
}, options);
}
});
});