Android 如何使用phonegap检查电话目录中的文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10294166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check a file's existence in phone directory with phonegap
提问by user992804
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 either phonegap methods, javascript or ajax?
我正在编写一个带有 Phonegap 1.4.1 和 Sencha 的 Android 应用程序,用于下载和读取 pdf 文件。如何使用 phonegap 方法、javascript 或 ajax 检查电话目录中是否存在该文件?
采纳答案by Darkaico
You could check if the file exists using the FileReader object from phonegap. You could check the following:
您可以使用 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);
回答by Thomas Solti
I had the same problem. I could not manage to get Darkaico's answer to work, but with the answer of Kurt I could make it work.
我有同样的问题。我无法得到达凯科的回答,但有了库尔特的回答,我可以让它发挥作用。
Here's my code:
这是我的代码:
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);
}
Then you only need to execute like this:
那么你只需要像这样执行:
checkIfFileExists("path/to/my/file.txt");
回答by Kurt Schuster
I get a handle to the file using the .getFile('fileName',{create:false},success,failure)
method. If I get the success
callback the file is there, otherwise any failure implies that there is a problem with the file.
我使用该.getFile('fileName',{create:false},success,failure)
方法获得文件的句柄。如果我得到success
回调文件就在那里,否则任何失败都意味着文件有问题。
回答by kris
The above answers did not work for me, but this did :
以上答案对我不起作用,但这确实适用:
window.resolveLocalFileSystemURL(fullFilePath, success, fail);
来自:http: //www.raymondcamden.com/2014/07/01/Cordova-Sample-Check-for-a-file-and-download-if-it-isnt-there
回答by alexdabest
Darkaico, Kurt and thomas answers didn't work for me. Here's what worked for me.
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');
}
});
回答by Víctor
@PassKit is correct, in my case i needed to add an eventlistener
@PassKit 是正确的,就我而言,我需要添加一个事件侦听器
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"
然后为函数“fsSuccess”中的值“fileSystemRoot”
var fileSystemRoot; // Global variable to hold filesystem root
function fsSuccess(fileSystem) {
fileSystemRoot = fileSystem.root.toURL();
}
the function "checkFileExists"
函数“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"
IOS 中的 var fileSystemRoot 返回“cdvfile://localhost/persistent/”并且文件存储在“//var/mobile/Containers/Data/Application/{AppID}/Documents”中
Many thanks to @PassKit, this run in synchronous mode and was tested in IOS 8.1
非常感谢@PassKit,它以同步模式运行并在 IOS 8.1 中进行了测试
回答by Marco Vereda Manchego
I've tested the following code snippet, and works quite well for me in PhoneGap 3.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())
{}
回答by Marek Marciniak
Kurt and Thomas gave better answers, because Darkaico's function not only checks if the file exists but also opens the file and reads it until the end.
Kurt 和 Thomas 给出了更好的答案,因为 Darkaico 的函数不仅会检查文件是否存在,还会打开文件并读取到最后。
This isn't a problem with small files, but if you check a large file then the app may crash.
这不是小文件的问题,但如果您检查大文件,则应用程序可能会崩溃。
Anyway, please use .getFile method - it's the best option.
无论如何,请使用 .getFile 方法 - 这是最好的选择。
回答by Gromish
note:
笔记:
when I get the filesystem I save it in a var under a macro pg object:
当我得到文件系统时,我将它保存在宏 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);
so my code is pretty simple...
所以我的代码很简单...
var fileExists = function(path, existsCallback, dontExistsCallback){
pg.fs.fileSystem.root.getFile(path, { create: false }, existsCallback, dontExistsCallback);
// "existsCallback" will get fileEntry as first param
}
回答by PassKit
The trouble with all of the current answers is that they depend on an asynchronous callback which updates a global variable. If you are checking multiple files, there is a risk that the variable will have been set by a different callback.
当前所有答案的问题在于它们依赖于更新全局变量的异步回调。如果您正在检查多个文件,则存在变量被不同回调设置的风险。
A basic Javascript XMLHttpRequest check is perfect for synchronously checking the file is accessible to via Javascript.
基本的 Javascript XMLHttpRequest 检查非常适合同步检查文件是否可以通过 Javascript 访问。
function checkFileExists(fileName){
var http = new XMLHttpRequest();
http.open('HEAD', fileName, false);
http.send(null);
return (http.status != 404);
}
Just pass in the full path to the file and then you can reliably use:
只需传入文件的完整路径,然后您就可以可靠地使用:
if (checkFileExists(fullPathToFile)) {
// File Exists
} else {
// File Does Not Exist
}
To store the root path in a variable you can use:
要将根路径存储在变量中,您可以使用:
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;
}