【问题标题】:How to check a file's existence in phone directory with phonegap如何使用phonegap检查电话目录中的文件是否存在
【发布时间】:2012-04-24 08:14:28
【问题描述】:

我正在使用 Phonegap 1.4.1 和 Sencha 编写一个下载和读取 pdf 文件的 Android 应用程序。如何使用 phonegap 方法、javascript 或 ajax 检查文件是否存在于电话目录中?

【问题讨论】:

    标签: javascript android ajax cordova


    【解决方案1】:

    我遇到了同样的问题。我无法让 Darkaico 的答案起作用,但有了 Kurt 的答案,我可以让它起作用。

    这是我的代码:

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

    那么你只需要这样执行:

    checkIfFileExists("path/to/my/file.txt");
    

    【讨论】:

    • 正如 Marek 所说,我的函数在打开文件时出现错误。所以你的解决方案更好更干净。
    • 只是要注意在算法的上下文中使用 checkIfFileExists 有点困难(例如它不能返回真/假,因为它是异步的),所以我建议将回调作为参数传递.类似于:checkIfFileExists(path, fileExists, fileDoesNotExist)
    • 如果使用 Angular,您可以使用延迟系统: function checkIfFileExists(path) { var def = $q.defer(); window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { fileSystem.root.getFile(path, { create: false }, def.resolve(true), def.resolve(false)); }, def.reject) ; //requestFileSystem 返回 def.promise; }
    • 我通过 ///storage/emulated/0/MyMusic/abc.mp3 作为我的文件的路径,但它说文件不存在。但它就在那里。
    【解决方案2】:

    我使用.getFile('fileName',{create:false},success,failure) 方法获得了文件的句柄。如果我得到success 回调文件就在那里,否则任何失败都意味着文件有问题。

    【讨论】:

      【解决方案3】:

      以上答案对我不起作用,但确实如此:

      window.resolveLocalFileSystemURL(fullFilePath, success, fail);
      

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

      【讨论】:

        【解决方案4】:

        您可以使用 phonegap 中的 FileReader 对象检查文件是否存在。 您可以检查以下内容:

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

        【讨论】:

        • 这对我不起作用(并且不知道它如何适用于任何人......方法 readAsDataURL 需要一个 blob,而不是字符串(路径),如 @987654321 中所述@文档
        • 我的文件的路径是 ///storage/emulated/0/MyMusic/abc.mp3。它说它必须是blob。请建议它是如何工作的。
        【解决方案5】:

        Darkaico、Kurt 和 thomas 的答案对我不起作用。这对我有用。

        $.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');
        }
        });
        

        【讨论】:

        • 太棒了,你节省了在 firefoxos 设备上测试我的 cordova 应用程序的时间
        【解决方案6】:

        @PassKit 是正确的,在我的情况下我需要添加一个事件监听器

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

        那么对于函数“fsSuccess”中的值“fileSystemRoot”

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

        函数“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
        }
        

        检查文件是否存在

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

        IOS 中的 var fileSystemRoot 返回“cdvfile://localhost/persistent/” 并且文件存储在“//var/mobile/Containers/Data/Application/{AppID}/Documents”中

        非常感谢@PassKit,它以同步模式运行并在 IOS 8.1 中进行了测试

        【讨论】:

        • 这给了我:XMLHttpRequest cannot load file://..... 跨源请求仅支持协议方案:http、data、app、https
        • 也与 .replace('file://','') 一起工作,但总是返回 true
        【解决方案7】:

        Kurt 和 Thomas 给出了更好的答案,因为 Darkaico 的函数不仅会检查文件是否存在,还会打开文件并读取它直到结束。

        这不是小文件的问题,但如果您检查大文件,则应用可能会崩溃。

        无论如何,请使用 .getFile 方法 - 这是最好的选择。

        【讨论】:

        • 您需要注意.getFile 方法是异步的——您的结果变量只会在文件系统回调返回时设置。如果您的代码尝试立即访问结果变量,它可能尚未设置。
        【解决方案8】:

        我已经测试了以下代码 sn-p,并且在 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())
        {}
        

        【讨论】:

        • 即使文件不存在也会返回 200
        【解决方案9】:

        所有当前答案的问题在于它们依赖于更新全局变量的异步回调。如果您正在检查多个文件,则变量可能会被不同的回调设置。

        基本的 Javascript XMLHttpRequest 检查非常适合同步检查文件是否可通过 Javascript 访问。

        function checkFileExists(fileName){
        
            var http = new XMLHttpRequest();
            http.open('HEAD', fileName, false);
            http.send(null);
            return (http.status != 404);
        }
        

        只需传入文件的完整路径,然后您就可以可靠地使用:

        if (checkFileExists(fullPathToFile)) {
            // File Exists
        } else {
            // File Does Not Exist
        }
        

        要将根路径存储在变量中,您可以使用:

        var fileSystemRoot; // Global variable to hold filesystem root
        
        window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsError);
        
        function fsError() {
            console.log("Failed to get Filesystem");
        }
        
        function fsSuccess(fileSystem) {
            console.log("Got Filesystem: Root path " + fileSystem.root);
        
            // save the file to global variable for later access
            window.fileSystemRoot = fileSystem.root;
        }   
        

        【讨论】:

        • @AshishNautiyal 感谢您的反对票 - 也许您会详细说明原因。
        【解决方案10】:

        注意:

        当我得到文件系统时,我将它保存在宏 pg 对象下的 var 中:

        pg = {fs:{}}    // I have a "GOTFS" function... a "fail" function
        pg.fs.filesystem = window.requestFileSystem(window.PERSISTENT, 0, pg.fs.GOTFS, pg.fs.fail);
        

        所以我的代码很简单...

        var fileExists = function(path, existsCallback, dontExistsCallback){
            pg.fs.fileSystem.root.getFile(path, { create: false }, existsCallback, dontExistsCallback);
                // "existsCallback" will get fileEntry as first param
            }
        

        【讨论】:

          【解决方案11】:

          此代码可用于自定义案例,完整文档在这里:download if not exist

          document.addEventListener("deviceready", init, false);
          
          //The directory to store data
          var store;
          
          //Used for status updates
          var $status;
          
          //URL of our asset
          var assetURL = "https://raw.githubusercontent.com/cfjedimaster/Cordova-Examples/master/readme.md";
          
          //File name of our important data file we didn't ship with the app
          var fileName = "mydatafile.txt";
          
          function init() {
          
          $status = document.querySelector("#status");
          
          $status.innerHTML = "Checking for data file.";
          
          store = cordova.file.dataDirectory;
          
          //Check for the file.
          window.resolveLocalFileSystemURL(store + fileName, appStart, downloadAsset);
          
          }
          
          function downloadAsset() {
          var fileTransfer = new FileTransfer();
          console.log("About to start transfer");
          fileTransfer.download(assetURL, store + fileName,
          function(entry) {
          console.log("Success!");
          appStart();
          },
          function(err) {
          console.log("Error");
          console.dir(err);
          });
          }
          
          //I'm only called when the file exists or has been downloaded.
          function appStart() {
          $status.innerHTML = "App ready!";
          }
          

          【讨论】:

            【解决方案12】:
                var fileexist;
            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!");
                fileexist = true;
            }
            function fileDoesNotExist(){
                alert("file does not exist");
               fileexist = false;
            }
            function getFSFail(evt) {
                console.log(evt.target.error.code);
                fileexist=false;
            }
            

            现在你可以使用条件了

            if(fileexist=="true"){
            //do something;
            }
            else if(fileexist=="false"){
            //do something else
            }
            

            【讨论】:

            • 这个解决方案的问题在于回调是异步的。您不能保证全局变量 fileexist 将准确反映文件的存在,尤其是在快速连续检查多个文件时。
            • 是的,必须改变策略。但是您对否决投票感到高兴:P:P
            • 我发布了一个同步解决方案。投反对票和评论投反对票的原因会提醒用户注意解决方案的潜在问题。
            【解决方案13】:

            如果您需要布尔兼容的方法...

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

            【讨论】:

            • 从匿名回调函数设置时,您的结果变量将超出范围。它也不会在函数返回之前设置,因此此解决方案将始终返回 false。
            【解决方案14】:

            我接受了上面的@Thomas Soti 回答,并将其精简为简单的是/否响应。

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

            更正....这不起作用。我现在正在解决这个问题。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-11-01
              • 1970-01-01
              • 1970-01-01
              • 2012-07-02
              • 2014-03-06
              相关资源
              最近更新 更多