Search code examples
cordovafileapi

How to check the exisisting directory in phonegap file api?


I have following code to store the captured images in separate directory in sdcard . But How to check whether particular directory exists or not ? Because if exists i want to display the images from that directory if not i want to save the captured images into new directory. Second part is there in my code. But help me with the first part.When it enters ondeviceready event i want to check , directory exists or not ???

function getImageURI(imageURI) {
        capturedImgId++;
        var imgId = "img"+capturedImgId;
        document.getElementById(imgId).src =  imageURI;
        document.getElementById(imgId).style.display = 'block';
        createButton(capturedImgId);
        var gotFileEntry = function(fileEntry) {
            alert("got image file entry: " + fileEntry.fullPath);
            var gotFileSystem = function(fileSystem) {

                fileSystem.root.getDirectory("BangaloreFolder", {
                    create : true
                }, function(dataDir) {

                    // copy the file
                    dataDir.getDirectory(today+"-T"+teamNo, {
                      create : true
                    },function(dataDir1) {
                      fileEntry.moveTo(dataDir1, capturedImgId+".jpg", null, fsFail);//try out with capturedImgId.jpg 
                    });

                }, dirFail);

            };
            // get file system to copy or move image file to
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem,
                    fsFail);
        };
        // resolve file system for image
        window.resolveLocalFileSystemURI(imageURI, gotFileEntry, fsFail);

        // file system fail
        var fsFail = function(error) {
            alert("failed with error code: " + error.code);

        };

        var dirFail = function(error) {
            alert("Directory error code: " + error.code);

        };
    }

Solution

  • I think your following code should be able to help you

     fileSystem.root.getDirectory("BangaloreFolder", {
                    create : true
                }, function(dataDir) {
    
                    // copy the file
                    dataDir.getDirectory(today+"-T"+teamNo, {
                      create : false
                    },function(dataDir1) {
                      fileEntry.moveTo(dataDir1, capturedImgId+".jpg", null, fsFail);//try out with capturedImgId.jpg 
                    });
    
                }, dirFail);
    

    NOTE: I have replaced create:false so it will call the dirFail function if directory will not be existing.

    You can have a different error call back method for this event. But a little more logic with it could help you achieve what you are looking for.