11

I am using cordova / phonegap and need to know if a file exists

Here's the code with the path and filename:

storeUrl = cordova.file.dataDirectory+'myfolder/myfile.mp3';

How can I check if this file exists?

Satch3000
  • 47,356
  • 86
  • 216
  • 346

2 Answers2

11

Try code from this link: https://cordovablogsblogs.wordpress.com/2015/06/10/how-to-check-a-files-existence-in-phone-directory-with-phonegap/. 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);
}
hubot
  • 393
  • 5
  • 18
  • tried checkIfFileExists(theurl + fileName); but that returns that the file does not exist when it does – Satch3000 Jan 09 '16 at 12:21
  • Check value of cordova.file.dataDirectory using instruction alert(cordova.file.dataDirectory);. – hubot Jan 09 '16 at 14:02
  • Thank you! What an awesome little set of functions to solve this problem. +lots –  Sep 07 '17 at 23:09
8

Update: Works on iOS too.

Try:

function checkIfFileExists(path){
    // path is the full absolute path to the file.
    window.resolveLocalFileSystemURL(path, fileExists, fileDoesNotExist);
}
function fileExists(fileEntry){
    alert("File " + fileEntry.fullPath + " exists!");
}
function fileDoesNotExist(){
    alert("file does not exist");
}

Found the solution here.

Works on Android. Will test on iOS and update this answer.

utamanna
  • 189
  • 2
  • 10