18

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

4

14 回答 14

32

我有同样的问题。我无法让 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");
于 2012-11-11T16:36:07.067 回答
21

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

于 2012-09-19T14:55:29.850 回答
21

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

window.resolveLocalFileSystemURL(fullFilePath, success, fail);

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

于 2015-01-21T04:05:06.247 回答
5

您可以使用 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);   
于 2012-05-23T18:53:18.240 回答
4

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');
}
});
于 2013-02-28T19:00:43.480 回答
2

@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 中进行了测试

于 2014-11-27T18:20:00.453 回答
1

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

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

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

于 2013-01-04T15:47:01.117 回答
1

我已经测试了以下代码片段,并且在 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())
{}
于 2013-10-29T14:20:10.573 回答
0

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

基本的 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;
}   
于 2013-10-01T15:28:44.563 回答
0

笔记:

当我得到文件系统时,我将它保存在宏 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
    }
于 2014-04-27T14:06:14.053 回答
0

此代码可用于自定义案例,完整文档在此处:如果不存在,请下载

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!";
}
于 2017-04-18T03:46:22.690 回答
-1
    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
}
于 2013-09-19T10:16:23.337 回答
-3

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

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;
}
于 2013-07-23T20:38:28.930 回答
-3

我接受了上面的@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) ;

更正....这不起作用。我现在正在修复。

于 2016-07-11T15:46:47.663 回答