如何使用 phonegap 检查文件在电话目录中是否存在
How to check a file's existence in phone directory with phonegap
我正在编写一个带有Phonegap 1.4.1和Sencha的Android应用程序,用于下载和读取pdf文件。如何使用 phonegap 方法、javascript 或 ajax 检查文件是否存在于电话目录中?
我遇到了同样的问题。我无法让达凯科的答案起作用,但有了库尔特的答案,我可以让它起作用。
这是我的代码:
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");
我使用 .getFile('fileName',{create:false},success,failure)
方法获取文件的句柄。如果我得到success
回调,文件就在那里,否则任何失败都意味着文件有问题。
上面的答案对我不起作用,但这确实:
window.resolveLocalFileSystemURL(fullFilePath, success, fail);
发件人 : http://www.raymondcamden.com/2014/07/01/Cordova-样本检查文件并下载(如果不存在)
您可以使用 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);
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');
}
});
@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();
}
函数"检查文件存在"
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 文件系统根返回我"cdvfile://localhost/persistent/"文件存储在"//var/mobile/Containers/Data/Application/{AppID}/Documents"中
非常感谢@PassKit,它在同步模式下运行并在IOS 8.1中进行了测试
Kurt和Thomas给出了更好的答案,因为Darkaico的函数不仅检查文件是否存在,而且还打开文件并读取它直到最后。
对于小文件来说,这不是问题,但是如果您检查大文件,则应用程序可能会崩溃。
无论如何,请使用.getFile方法 - 这是最好的选择。
测试了以下代码片段,并且在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())
{}
所有当前答案的问题在于它们依赖于更新全局变量的异步回调。 如果要检查多个文件,则存在变量由其他回调设置的风险。
基本的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;
}
注意:
当我得到文件系统时,我将其保存在宏 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
}
此代码可用于自定义案例,完整文档在此处:如果不存在,请下载
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!";
}
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
}
如果您需要一个布尔兼容的方法...
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;
}
我采用了上面的@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) ;
校正。。。。这行不通。 我现在正在努力修复。
- 用于检查数组中是否存在元素的javascript自定义方法
- 是否存在React Native“;WEB代码安全防护”;
- 验证会话中是否存在对象's数组
- 如何查找值是否存在于二叉树中
- 检查是否存在使用chrome扩展的javascript库
- 是否存在Javascript Liferay Service库的文档?如何处理错误情况
- 测试mongo脚本中是否存在参数
- 检查搜索结果是否存在多次如果是,则在Javascript中只显示一个结果
- 检查数组中是否存在字符串值,并返回找到的数组值js
- 如何通过json对象选项卡中的Id来检查对象是否存在
- 检查是否存在任意控制器/操作
- Javascript滑块不滑动,如何判断是否存在JS冲突
- 根据手机上是否存在文件,在jQuery mobile中动态填充列表视图
- javascript测试是否存在两个标志中的任何一个
- 如何使用javascript检查移动sd卡中是否存在文件
- 当提供函数名称时,检查函数是否存在于同一作用域中
- 需要帮助使用JQuery.inArray()检查值是否存在
- 确定元素是否存在
- 使用javascript检查服务器上是否存在html文件
- 是否存在类似ExtJS 4的框架;正常的“;网站