Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 either phonegap methods, javascript or ajax?

like image 514
user992804 Avatar asked Apr 24 '12 08:04

user992804


5 Answers

I had the same problem. I could not manage to get Darkaico's answer to work, but with the answer of Kurt I could make it work.

Here's my code:

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);
}

Then you only need to execute like this:

checkIfFileExists("path/to/my/file.txt");
like image 141
Thomas Solti Avatar answered Nov 10 '22 13:11

Thomas Solti


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.

like image 21
Kurt Schuster Avatar answered Nov 10 '22 12:11

Kurt Schuster


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

like image 21
kris Avatar answered Nov 10 '22 12:11

kris


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);   
like image 5
Darkaico Avatar answered Nov 10 '22 11:11

Darkaico


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');
}
});
like image 4
alexdabest Avatar answered Nov 10 '22 13:11

alexdabest