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

后端 未结 14 1986
太阳男子
太阳男子 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:50

    If you need a boolean-compatible method...

    function checkIfFileExists(path){
        var result = false;
    
        window.requestFileSystem(
            LocalFileSystem.PERSISTENT, 
            0, 
            function(fileSystem){
                fileSystem.root.getFile(
                    path, 
                    { create: false }, 
                    function(){ result = true; }, // file exists
                    function(){ result = false; } // file does not exist
                );
            },
            getFSFail
        ); //of requestFileSystem
    
        return result;
    }
    
    0 讨论(0)
  • 2020-12-05 11:51

    @PassKit is correct, in my case i needed to add an eventlistener

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
           window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
           window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsError);
    }
    

    then for the value "fileSystemRoot" in the funtion "fsSuccess"

    var fileSystemRoot; // Global variable to hold filesystem root
    
    function fsSuccess(fileSystem) {
           fileSystemRoot = fileSystem.root.toURL();
    }
    

    the function "checkFileExists"

    function checkFileExists(fileName) {
        var http = new XMLHttpRequest();
        http.open('HEAD', fileName, false);
        http.send(null);
        if (http.status.toString() == "200") {
            return true;
        }
        return false
    }
    

    for check if the file exists

    if (checkFileExists(fileSystemRoot + "fileName")) {
         // File Exists
    } else {
         // File Does Not Exist
    }
    

    the var fileSystemRoot in IOS return me "cdvfile://localhost/persistent/" and the files was store in "//var/mobile/Containers/Data/Application/{AppID}/Documents"

    Many thanks to @PassKit, this run in synchronous mode and was tested in IOS 8.1

    0 讨论(0)
提交回复
热议问题