2012-04-24 17 views

回答

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); 
+1

對於我這個不到風度的工作(不知道它如何能爲任何工作....方法readAsDataURL需要一個blob,而不是字符串(路徑),如[的FileReader](http://www.javascripture.com/FileReader)DOC – 2016-02-25 11:38:49

+0

路徑指定到我的文件是本///存儲/模擬/ 0/MyMusic/ABC MP3播放。它說,它必須是一滴。請建議將如何工作。 – Murtuza 2016-09-18 13:51:07

+2

這是不正確的答案。 – PhonegapExpert 2016-11-09 20:56:15

21

我得到一個處理使用.getFile('fileName',{create:false},success,failure)方法的文件。如果我得到回調文件success,否則任何失敗都意味着文件有問題。

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"); 
+2

由於馬立克說我的函數有打開的文件中的錯誤。所以,你的解決方案是更好的和乾淨的。 – Darkaico 2013-02-06 20:09:36

+0

只是要注意,使用checkIfFileExists有點困難在算法的上下文內(例如,它不能返回true/false,因爲它是異步的),所以我建議將回調作爲參數傳遞。例如:checkIfFileExists(path,fileExists,fileDoesNotExist) – 2014-09-10 08:21:11

+0

如果使用角度可以使用延遲系統: function checkIfFileExists(path){var def = $ q.defer(); window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(fileSystem){file} {fileSystem.root.getFile {path,{create:false},def.resolve(true),def.resolve(false)); def 。拒絕); // request requestFileSystem return def.promise; } – Kiwi 2015-11-05 08:19:17

1

科特托馬斯給了更好的答案,因爲Darkaico的功能不僅會檢查文件存在,但也打開文件並讀取它直到結束。

這不是小文件的問題,但是如果你檢查一個大文件,那麼應用程序可能會崩潰。

無論如何,請使用.getFile方法 - 這是最好的選擇。

+0

你是對的。感謝我將考慮到的反饋 – Darkaico 2013-02-06 20:10:15

+0

您需要注意'.getFile'方法是異步的 - 只有在文件系統回調已經返回時纔會設置結果變量。如果您的代碼試圖立即訪問結果變量,它可能尚未設置。 – PassKit 2013-10-01 15:39:12

4

Darkaico,Kurt和托馬斯的答案並不適合我。這是爲我工作的。

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

太棒了,您可以在firefoxos設備上保存測試我的科爾多瓦應用程序的日子 – caiofior 2016-06-03 15:34:29

-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; 
} 
+0

從匿名回調函數設置時,您的結果變量將超出範圍。它也不會在函數返回之前設置,因此此解決方案將始終返回false。 – PassKit 2013-10-01 15:34:18

-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 
} 
+0

該解決方案的問題在於它的回調是異步的。您不能保證全局變量fileexist將準確反映文件的存在,特別是在快速連續檢查多個文件時。 – PassKit 2013-10-01 06:14:51

+0

是的,不得不改變策略。但是你對下來投票感到高興:P:P – 2013-10-01 11:50:01

+0

我發佈了一個同步解決方案。向下投票並評論投票退出的原因提醒用戶解決方案的潛在問題。 – PassKit 2013-10-01 15:30:42

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; 
} 
+0

@AshishNautiyal感謝您的反對 - 也許您會善意闡述爲什麼。 – PassKit 2013-10-03 07:09:23

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()) 
{} 
+0

我經常看到類似這樣的內容:「不要玩原型」...... – Gromish 2014-04-27 13:52:47

+0

即使文件不存在也返回200 – 2015-12-06 17:47:52

0

注:

時,我得到了文件系統I將其保存在一個VAR宏PG對象下:

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 
    } 
2

@PassKit是正確的,在我的情況,我需要添加一個事件監聽

document.addEventListener("deviceready", onDeviceReady, false); 
function onDeviceReady() { 
     window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; 
     window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsError); 
} 

然後在funtion 「fsSuccess」

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 
} 
值 「fileSystemRoot」

在IOS的VAR fileSystemRoot還給我 「cdvfile://本地主機/永久/」 個並且文件是存儲在「// VAR /移動/容器/數據/應用/ {的AppID} /文檔」

非常感謝@PassKit,該運行在同步模式和測試在IOS 8.1

+0

這給了我:XMLHttpRequest無法加載文件:// .....只有交叉原點請求支持協議方案:http,data,app,https – dragonmnl 2015-10-18 15:20:20

+0

也可以使用.replace('file://','')作品,但始終返回true – dragonmnl 2015-10-18 15:37:31

-3

我把@Thomas技工機構回答以上和修剪下來到一個簡單的是/否響應。

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) ; 

糾正....這是行不通的。我現在正在修復此問題。

0

該代碼可用於定製的情況下,完整的文檔在這裏:download if not exist

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!"; 
} 
相關問題