如何使用phonegap检查电话目录中的文件是否存在

use*_*804 18 javascript ajax android cordova

我正在编写一个带有Phonegap 1.4.1和Sencha的Android应用程序,用于下载和读取pdf文件.如何使用phonegap方法,javascript或ajax检查电话目录中是否存在该文件?

Tho*_*lti 32

我有同样的问题.我无法得到Darkaico的工作答案,但是凭借Kurt的答案,我可以让它发挥作用.

这是我的代码:

function checkIfFileExists(path){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
        fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
    }, getFSFail); //of requestFileSystem
}
function fileExists(fileEntry){
    alert("File " + fileEntry.fullPath + " exists!");
}
function fileDoesNotExist(){
    alert("file does not exist");
}
function getFSFail(evt) {
    console.log(evt.target.error.code);
}
Run Code Online (Sandbox Code Playgroud)

然后你只需要像这样执行:

checkIfFileExists("path/to/my/file.txt");
Run Code Online (Sandbox Code Playgroud)

  • 正如Marek所说我的函数有一个错误打开文件.所以你的解决方案更好,更干净. (2认同)

小智 21

我使用该.getFile('fileName',{create:false},success,failure)方法获取文件的句柄.如果我收到success回调文件就在那里,否则任何失败都意味着该文件存在问题.


kri*_*ris 20

以上答案对我不起作用,但这样做:

window.resolveLocalFileSystemURL(fullFilePath, success, fail);
Run Code Online (Sandbox Code Playgroud)

来自:http://www.raymondcamden.com/2014/07/01/Cordova-Sample-Check-for-a-file-and-download-if-it-isnt-there


Dar*_*ico 5

您可以使用phonegap中的FileReader对象检查文件是否存在.你可以检查以下内容:

var reader = new FileReader();
var fileSource = <here is your file path>

reader.onloadend = function(evt) {

    if(evt.target.result == null) {
       // If you receive a null value the file doesn't exists
    } else {
        // Otherwise the file exists
    }         
};

// We are going to check if the file exists
reader.readAsDataURL(fileSource);   
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用(并且不知道它如何对任何人起作用....readAsDataURL 方法需要一个 blob,而不是一个字符串(路径),如 [FileReader](http://www. javascripture.com/FileReader) 文档 (2认同)