[英]How to check a file's existence in phone directory with phonegap
我正在編寫一個帶有Phonegap 1.4.1和Sencha的Android應用程序,用於下載和讀取pdf文件。 如何使用phonegap方法,javascript或ajax檢查電話目錄中是否存在該文件?
我有同樣的問題。 我無法得到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");
我使用.getFile('fileName',{create:false},success,failure)
方法獲取文件的句柄。 如果我獲得success
回調文件就在那里,否則任何失敗都意味着該文件存在問題。
以上答案對我不起作用,但這樣做:
window.resolveLocalFileSystemURL(fullFilePath, success, fail);
來自: http : //www.raymondcamden.com/2014/07/01/Cordova-Sample-Check-for-a-file-and-download-if-it-isnt-there
您可以使用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是正確的,在我的情況下,我需要添加一個eventlistener
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中進行了測試
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) ;
更正....這不起作用。 我正在修復此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.