不通过循环/上传后,不删除文件

时间:2014-01-24 22:42:02

标签: javascript cordova

我的问题是如何修复下面的方法并理解为什么不起作用:

智能手机有10个音频文件。 LOOP FOR浏览所有音频文件,然后转到ft.upload。哪个错了,做10次相同的第10个音频文件(最后一个音频文件)。 如何为LOOP FOR浏览第一个文件然后上传并删除它并保持循环直到该文件夹​​为空?在我的文件成功上传后,entry.remove(success, fail);没有删除文件。

任何建议都会有所帮助。

function uploadAudioFiles() {
    var localFolder = "Sounds";
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
        fs.root.getDirectory(localFolder, {create:false}, function(dirEntry){
            var dirReader = dirEntry.createReader();
            dirReader.readEntries(function(entries) {
                for(var i = 0; i < entries.length; i++) {
                    console.log(entries);
                    var entry = entries[i];
                        //print all the audio 1 to 10.
                    var ft = new FileTransfer();
                    if (entry.isFile){
                        var path = entry.fullPath;
                        var name = entry.name;
                //var reader = new FileReader();
                //reader.readAsText(path);
                //print 10x the same audio 10th on success.
                ft.upload(path, "http://111.111.11.1:8080/hello/world/", function(result) {
                    console.log('Upload success: ' + result.responseCode);
                    console.log(result.bytesSent + ' bytes sent');
                    console.log("path:" + path);
                    //it calls success, but is not removing on my smartphone
                    fileSystem.root.getFile(path, {create: false, exclusive: false}, success, fail);
                },
                function(error) {
                    console.log('Error uploading file ' + path + ': ' + error.code);
                },
                { fileName: name });
            }
        }
    }, fail);
        }, fail);
    });
}

function success(entry) {
    console.log("Removal succeeded" + entry.name + entry.fullPath + entry);
}
function fail(error) {
    alert('Error removing file: ' + error.code);
}

1 个答案:

答案 0 :(得分:1)

试试这个。将您的上传调用包装在一个匿名函数中,您可以使用该条目作为参数立即执行该函数。这样您就可以“捕获”匿名函数内的当前条目值。问题可能在于,由于条目的上传是在回调函数中完成的,因此在循环的每次迭代中都会覆盖条目的值。我之前遇到过类似的问题,可以这样解决。我希望我的所有括号都正确。

if (entry.isFile){
    var path = entry.fullPath;
    var name = entry.name;
    (function(currentPath, currentName) {
        ft.upload(currentPath, "http://111.111.11.1:8080/hello/world/", function(result) {
            console.log('Upload success: ' + result.responseCode);
            console.log(result.bytesSent + ' bytes sent');
            console.log("path:" + currentPath);
            //it calls success, but is not removing on my smartphone
            fileSystem.root.getFile(currentPath, {create: false, exclusive: false}, success, fail);
        },
        function(error) {
            console.log('Error uploading file ' + currentPath + ': ' + error.code);
        },
        { fileName: currentName });
    })(path, name);
}