How to check a file's existence in phone directory with phonegap

后端 未结 14 1987
太阳男子
太阳男子 2020-12-05 10:49

I\'m writing an Android application with Phonegap 1.4.1 and Sencha that downloads and reads pdf files. How can I check whether the file exists in the phone directory using e

相关标签:
14条回答
  • 2020-12-05 11:33

    I took @Thomas Soti answer above and trimmed it down to a simple yes/no response.

    function fileExists(fileName) {
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
          fileSystem.root.getFile(cordova.file.dataDirectory + fileName, { create: false }, function(){return true}, function(){return false});
      }, function(){return false}); //of requestFileSystem
    }
    // called as
    if (fileExists("blah.json")) {
    or
    var fe = fileExists("blah.json) ;
    

    Correction....this does NOT work. I am working on the fix now.

    0 讨论(0)
  • 2020-12-05 11:36

    You could check if the file exists using the FileReader object from phonegap. You could check the following:

    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);   
    
    0 讨论(0)
  • 2020-12-05 11:42

    The above answers did not work for me, but this did :

    window.resolveLocalFileSystemURL(fullFilePath, success, fail);
    

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

    0 讨论(0)
  • 2020-12-05 11:44

    I've tested the following code snippet, and works quite well for me in PhoneGap 3.1

    String.prototype.fileExists = function() {
    filename = this.trim();
    
    var response = jQuery.ajax({
        url: filename,
        type: 'HEAD',
        async: false
    }).status;  
    
    return (response != "200") ? false : true;}
    
    if (yourFileFullPath.fileExists())
    {}
    
    0 讨论(0)
  • 2020-12-05 11:48

    I get a handle to the file using the .getFile('fileName',{create:false},success,failure) method. If I get the success callback the file is there, otherwise any failure implies that there is a problem with the file.

    0 讨论(0)
  • 2020-12-05 11:48

    Darkaico, Kurt and thomas answers didn't work for me. Here's what worked for me.

    $.ajax({
    url:'file///sdcard/myfile.txt',
    type:'HEAD',
    error: function()
    {
        //file not exists
    alert('file does not exist');
    },
    success: function()
    {
        //file exists
    alert('the file is here');
    }
    });
    
    0 讨论(0)
提交回复
热议问题