Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检查文件';存在于带有phonegap的电话目录中_Javascript_Android_Ajax_Cordova - Fatal编程技术网

Javascript 如何检查文件';存在于带有phonegap的电话目录中

Javascript 如何检查文件';存在于带有phonegap的电话目录中,javascript,android,ajax,cordova,Javascript,Android,Ajax,Cordova,我正在用Phonegap 1.4.1和Sencha编写一个Android应用程序,可以下载和读取pdf文件。如何使用phonegap方法、javascript或ajax检查文件是否存在于电话目录中?您可以使用phonegap中的FileReader对象检查文件是否存在。 您可以检查以下内容: var reader = new FileReader(); var fileSource = <here is your file path> reader.onloadend = func

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

您可以使用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);   
var reader=newfilereader();
var fileSource=
reader.onloadend=函数(evt){
if(evt.target.result==null){
//如果收到空值,则文件不存在
}否则{
//否则该文件将存在
}         
};
//我们将检查该文件是否存在
reader.readAsDataURL(fileSource);

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

我也有同样的问题。我无法得到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");

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

这对于小文件来说不是问题,但是如果你检查一个大文件,那么应用程序可能会崩溃


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

Darkaico、Kurt和thomas answers对我不起作用。这是对我有用的东西

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

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

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;
}
现在可以使用条件

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

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

基本的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;
}   

我已经测试了以下代码片段,在PhoneGap3.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())
{}
注:

当我获取文件系统时,我将其保存在宏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
    }

@PassKit是正确的,在我的例子中,我需要添加一个eventlistener

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
       window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
       window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsError);
}
然后输入函数“fsSuccess”中的值“fileSystemRoot”

函数“checkFileExists”

用于检查文件是否存在

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中进行了测试。上面的答案对我不起作用,但它确实起了作用:

window.resolveLocalFileSystemURL(fullFilePath, success, fail);

from:

我把上面的@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) ;

更正……这不起作用。我现在正在进行修复。

此代码可用于自定义案例,完整文档如下:


正如Marek所说,我的函数有一个打开文件的错误。因此,您的解决方案更好、更干净。请注意,在算法的上下文中使用checkIfFileExists有点困难(例如,它不能返回true/false,因为它是异步的),因此我建议将回调作为参数传递。类似于:checkIfFileExists(path,fileExists,fileDoesNotExist)如果使用angular,则可以使用延迟系统:函数checkIfFileExists(path){var def=$q.defer();窗口.requestFileSystem(LocalFileSystem.PERSISTENT,0,函数(fileSystem){fileSystem.root.getFile(path,{create:false},def.resolve(true),def.resolve(false));},def.reject);//of requestFileSystem return def.promise;}我传递了///storage/emulated/0/MyMusic/abc.mp3作为我文件的路径,但它说文件不存在。这个解决方案的问题在于,它的回调是异步的。您不能保证全局变量fileexist将准确反映文件的存在,尤其是在快速连续检查多个文件时。是的,您必须更改策略。但是你对否决投票感到高兴:P:PI已经发布了一个同步解决方案。向下投票和注释向下投票的原因会提醒用户解决方案可能存在的问题。从匿名回调函数设置结果变量时,结果变量将超出范围。在函数返回之前也不会设置它,因此此解决方案将始终返回false。您需要注意,
.getFile
方法是异步的-只有在文件系统回调返回时才会设置结果变量。如果您的代码试图立即访问结果变量,则该变量可能尚未设置。@AshishNautiyal感谢您的否决票-也许您可以详细说明原因。这给了我:XMLHttpRequest无法加载file://..... 跨源请求仅支持协议方案:http、data、app、httpsalso with.replace('file://','')工作,但始终返回TrueT返回200,即使文件不存在此选项对我不起作用(并且不知道如何对任何选项起作用….readAsDataURL方法需要一个blob,而不是一个字符串(路径),正如我的文件的docpath中所指定的,这是///storage/emulated/0/MyMusic/abc.mp3。它说它一定是blob。请建议它的工作方式。太好了,您可以省去在firefoxos设备上测试我的cordova应用程序的时间
if (checkFileExists(fileSystemRoot + "fileName")) {
     // File Exists
} else {
     // File Does Not Exist
}
window.resolveLocalFileSystemURL(fullFilePath, success, fail);
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) ;
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!";
}