Cordova實現文件操作,本篇文章講述的是在IOS和Android上實現以下兩種需求:
1,創建文件夾和文件,從數據庫獲取數據并寫入到文件;
2,獲取指定目錄文件夾下文件,并讀取文件數據;
先上效果圖:
創建文件夾和文件,從數據庫獲取數據并寫入到文件


獲取指定目錄文件夾下文件,并讀取文件數據

進入正題,下面是具體實現過程:
文件操作使用了cordova-plugin-file插件,插件地址:https://github.com/apache/cordova-plugin-file;
一,準備工作
1,安裝cordova-plugin-file插件
在工程目錄下執行以下命令:
sudo cordova plugin add cordova-plugin-file2,在 config.xml 文件中配置持久化文件保存位置(Persistent storage location)IOS中,默認配置或如下配置時,會保存在程序的 Documents 文件目錄下
<PReference name="iosPersistentFileLocation" value="Compatibility" />要想保存到應用的 Library 文件夾下,可以如下配置<preference name="iosPersistentFileLocation" value="Library" />Android中,默認配置或如下配置時,會保存在 /data/data/<packageId> 下面<preference name="AndroidPersistentFileLocation" value="Internal" />要想保存到SD卡或等效的存儲分區,可以如下配置:<preference name="AndroidPersistentFileLocation" value="Compatibility" />我是如下配置的:
<preference name="iosPersistentFileLocation" value="Compatibility" /><preference name="AndroidPersistentFileLocation" value="Compatibility" />3,在 config.xml 文件中配置文件系統
<preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" /><preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />至于各種value的區別,這里就懶得寫了,直接貼上官方原話:
Android
files: The application's internal file storage directoryfiles-external: The application's external file storage directorysdcard: The global external file storage directory (this is the root of the SD card, if one is installed). You must have theandroid.permission.WRITE_EXTERNAL_STORAGEpermission to use this.cache: The application's internal cache directorycache-external: The application's external cache directoryassets: The application's bundle (read-only)root: The entire device filesystemAndroid also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
iOS
library: The application's Library directorydocuments: The application's Documents directorycache: The application's Cache directorybundle: The application's bundle; the location of the app itself on disk (read-only)root: The entire device filesystemBy default, the library and documents directories can be synced to iCloud. You can also request two additional filesystems,
library-nosyncanddocuments-nosync, which represent a special non-synced directory within the/Libraryor/Documentsfilesystem.我是如下配置的:
<preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" /><preference name="AndroidExtraFilesystems" value="sdcard" />4,Android平臺需要配置文件權限
在AndroidManifest.xml中如下配置:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />二,具體實現要下班了,就不詳細講解了,直接貼代碼://文本內容var tasksStr = '';/** 從數據庫查詢數據,寫入到指定目錄下文件中* */function exportDataFromDb() { selectDataFromConcernsDeviceInfos('admin', function (result) { if (result.length != 0) { for (var i = 0; i < result.length; i++) { tasksStr = tasksStr + JSON.stringify(result[i]); } console.log(tasksStr); createAndWriteFile(); } else { console.log('no data'); } });}/* * 打開或創建文件夾,創建文件并寫入內容 * Android:sdcard/xbrother/assets目錄 * IOS:cdvfile://localhost/persistent/xbrother/assets目錄 * 文件目錄存在則打開,不存在則創建 * */function createAndWriteFile() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) { console.log('打開的文件系統: ' + fs.name); fs.root.getDirectory('xbrother', {create: true}, function (dirEntry) { dirEntry.getDirectory('assets', {create: true}, function (subDirEntry) { subDirEntry.getFile("task.json", {create: true, exclusive: false}, function (fileEntry) { fileEntry.name == 'task.json'; fileEntry.fullPath == 'xbrother/assets/task.json'; //文件內容 var dataObj = new Blob([tasksStr], {type: 'text/plain'}); //寫入文件 writeFile(fileEntry, dataObj); }, onErrorCreateFile); }, onErrorGetDir); }, onErrorGetDir); }, onErrorLoadFs);}/** 依次打開指定目錄文件夾,讀取文件內容 * Android:sdcard/xbrother/assets/task.json * IOS:cdvfile://localhost/persistent/xbrother/assets/task.json* 目錄和文件存在則打開,不存在則退出* */function getAndReadFile() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) { console.log('打開的文件系統: ' + fs.name); fs.root.getDirectory('xbrother', {create: false}, function (dirEntry) { dirEntry.getDirectory('assets', {create: false}, function (subDirEntry) { subDirEntry.getFile("task.json", {create: false, exclusive: false}, function (fileEntry) { console.log("是否是個文件?" + fileEntry.isFile.toString()); fileEntry.name == 'task.json'; fileEntry.fullPath == 'xbrother/assets/task.json'; readFile(fileEntry); }, onErrorCreateFile); }, onErrorGetDir); }, onErrorGetDir); }, onErrorLoadFs);}//將內容數據寫入到文件中function writeFile(fileEntry, dataObj) { //創建一個寫入對象 fileEntry.createWriter(function (fileWriter) { //文件寫入成功 fileWriter.onwriteend = function () { console.log("Successful file write..."); }; //文件寫入失敗 fileWriter.onerror = function (e) { console.log("Failed file write: " + e.toString()); }; //寫入文件 fileWriter.write(dataObj); });}//讀取文件function readFile(fileEntry) { fileEntry.file(function (file) { var reader = new FileReader(); reader.onloadend = function () { $$('#file_content_info').html(this.result); console.log("file read success:" + this.result); }; reader.readAsText(file); }, onErrorReadFile);}//FileSystem加載失敗回調function onErrorLoadFs(error) { console.log("文件系統加載失敗!")}//文件夾創建失敗回調function onErrorGetDir(error) { console.log("文件夾創建失敗!")}//文件創建失敗回調function onErrorCreateFile(error) { console.log("文件創建失敗!")}//讀取文件失敗響應function onErrorReadFile() { console.log("文件讀取失敗!");}三,注意問題關于ios文件拷出問題
1,如果想要將ios中創建的文件拷貝出來,需要在.plist作如下配置:
<key>UIFileSharingEnabled</key>當然也可以直接在Xcode中配置:
2,不建議用iTunes拷貝。以我血的教訓為例,我明明創建了 /xbrother/assets目錄,并在目錄下創建了task.json文件,然而用iTunes查看時,卻只能看到xbrother文件夾,下一層級的assets文件夾和文件夾下task.json文件根本就看!不!到!多次插拔手機還是無解,一直以為是我代碼寫的有問題。反復檢查代碼確認沒問題后,換一款軟件(同步助手)來查看,居然都能看見了!如上面效果圖中所示。白白在這個問題上郁悶一個多小時。當然直到現在還是沒搞懂,哪位仁兄知道原因的話請務必不吝賜教。
3,在.plist中配置了iTunes文件共享權限后,在上架到AppStore時,需要備注說明開啟此權限的原因。我提交后沒能通過蘋果審核,此部分蘋果反饋如下:
Information Needed
We began the review of your app but aren't able to continue because we need additional information about your app.At your earliest opportunity, please review the following question(s) and provide as much detailed information as you can. The more information you can provide upfront, the sooner we can complete your review.- What is the purpose of enabling iTunes File Sharing? Please explain the need for this, and where the usage can be found in your binary.Once you reply to this message in Resolution Center with the requested information, we can proceed with your review.
其實這個插件功能挺強大,本篇文章只講了自己在項目中用到的部分,想要全面了解這個插件的功能,建議直接github看項目文檔,地址是:https://github.com/apache/cordova-plugin-file/blob/master/README.md。
下面這篇文章也寫的特別好:
Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)
關于文件上傳下載部分,可以結合插件cordova-plugin-file-transfer實現,關于這部分,下面這篇文章講的特別好:
Cordova - fileTransfer插件的使用詳解(實現文件上傳、下載)
以上寫的有不對的地方歡迎各位朋友批評指正。
新聞熱點
疑難解答