我一直在使用 PhoneGap 2.9.0(带构建)从网站下载文件以存储在我的 Android 设备上的 SD 卡上。
我正在寻找下载多个文件并检查所有这些请求是否已成功完成的解决方案。
有人告诉我使用 jQuery.Deffered 是可能的 但我还没有在任何代码中使用它,我正在努力理解它。
现有代码在理论上工作正常,但仅检查我数组中的最后一次下载何时成功下载,但有时最后一次下载有时会先于其他下载成功返回。
我的代码类似于以下内容:
var ft = new FileTransfer();
var online = [
'http://google.com/img/1.jpg',
'http://google.com/img/2.jpg',
'http://google.com/img/3.jpg'
];
var sdcard = 'file:///storage/sdcard0/';
$.each( online, function(k,v) {
ft.download(
online[k],
sdcard,
win,
fail
);
}
var win = function(success, counter){
// check if counter is last element in array
// redirect user to page if last element
}
var fail = function(error){
console.log(error);
}
最佳答案
我最终使用了 simon mcondalds 解决方案并且没有使用 jQuery.deferred
基本上,当成功检索到一个项目时,将我必须从 Web 获取的所有项目放入一个数组中,只需从数组中删除该项目,然后再次调用相同的函数。最终 array.length 将有
https://gist.github.com/macdonst/3835045
此处示例代码:
var remoteFiles = [];
function downloadRemotePDF() {
var local2User = JSON.parse( localStorage["locallessons"] );
$.each(local2User, function(key) {
remoteFiles.push(optionsJSON + local2User[key].idcountries + '/' + local2User[key].idcurriculum + '/' + local2User[key].idoptions + '/pdf/' + local2User[key].pdfname);
}
downloadFile();
}
function downloadFile() {
// No files left, stop downloading
if (remoteFiles.length == 0) {
return;
}
var remoteFile = remoteFiles.pop();
var localFileName = remoteFile.substring(remoteFile.lastIndexOf('/')+1);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(localFileName, {create: true, exclusive: false}, function(fileEntry) {
var localPath = fileEntry.fullPath;
if (device.platform === "Android" && localPath.indexOf("file://") === 0) {
localPath = localPath.substring(7);
}
var ft = new FileTransfer();
ft.download(remoteFile, localPath, function(entry) {
// Do what you want with successful file downloaded and then
// call the method again to get the next file
downloadFile();
}, fail);
}, fail);
}, fail);
}
关于javascript - 使用 PhoneGap 检查何时下载了多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18847763/