加菲貓應用程式APP的功能之一,是可以下載離線檔案。但是在下載之前,希望能檢查行動裝置裡面是否已經有下載過同樣檔案,並做出不同的顯示。
檢查檔案是否存在的語法(可以直接寫在HTML檔裡面):
<script type="text/javascript"> 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); } </script> <input type="button" value="Check" onClick="checkIfFileExists('path/to/your/file.txt');"/>
要在頁面載入時就做檢查:
document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Now safe to use the Cordova API }
參考來源:http://docs.phonegap.com/en/2.3.0/cordova_events_events.md.html#deviceready
檢查完成之後輸出對應結果的字串(加入檢查結果的程式碼中):
document.getElementById('message_text').innerHTML="this is your message";
記得在下方加入一個對應的div標籤顯示此訊息
<div id="message_text"></div>
最後完整的程式內容:
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="cordova-2.3.0.js"></script> </head> <body> <script type="text/javascript"> document.addEventListener("deviceReady", onDeviceReady, false); function onDeviceReady() { // Now safe to use the PhoneGap API window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){ fileSystem.root.getFile('path/to/your/file.txt', { create: false }, fileExists, fileDoesNotExist); }, getFSFail); //of requestFileSystem function fileExists(fileEntry){ document.getElementById('message_text').innerHTML="File exists"; } function fileDoesNotExist(){ document.getElementById('message_text').innerHTML="File doesn't exist"; } function getFSFail(evt) { document.getElementById('message_text').innerHTML="System error"; } } </script> <div id="message_text"></div> </body> </html>