cordova檔案系統建立資料夾與讀寫檔案例項
阿新 • • 發佈:2018-12-26
一、cordova 檔案系統
1. 安裝外掛
cordova 需要安裝外掛才能對對手機檔案系統進行操作
cordova plagin add cordova-plugin-file
2. 需要了解的外掛api
1 . cordova.file.externalRootDirectory ;
/*獲取手機外部儲存根路徑,與其類似的api請參考開發文件 */
2 . window.resolveLocalFileSystemURI(uir,function(entry){},
errorCallback);
/* uir 就是之前的路徑 ,function(entry) {},寫法不一,函式可以寫在外邊,主要是為了接受entry例項
errorCallback 錯誤回撥
*/
3 . Entry.getDirectory("dirName", {create: true,exclusive: false},
function (dirEntry) {},
onErrorGetDir);
/* 建立或開啟資料夾 類似三個引數,第一個為建立或開啟資料夾名,
{create: true,exclusive: false}為 建立/開啟方式,exclusive: false,
代表會若存在該資料夾會重寫,因此可以預設true
onErrorGetDir 建立資料夾失敗
*/
4. dirEntry.getFile( fileName, { create: true, exclusive: false },
function (fileEntry) {
}, onErrorCreateFile);
/*與建立檔案類似*/
5 .fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function () {
fileWriter.onwrite=function () {}
fileWriter.onerror = function (e) {
};
fileWriter.write(dataObj);//寫檔案
});
二、例項
1.建立資料夾
以下程式碼在手機外部儲存中先建立了一個”表型採集模版與資料”目錄/資料夾
再在其中分別建立了”data”,”template”,“photo”三個同級資料夾。
document.addEventListener("deviceready",initFileSystem,false);
//初始化檔案系統
function initFileSystem() {
writeDirectory();
}
function writeDirectory(){
var dirUri = cordova.file.externalRootDirectory;
window.resolveLocalFileSystemURI(dirUri,function (entry) {
entry.getDirectory("表型採集模版與資料", {
create: true,
},function (dirEntry) {
dirEntry.getDirectory('template', { create: true }, function (subDirEntry) {
}, onErrorGetDir);
dirEntry.getDirectory('data', { create: true }, function (subDirEntry) {
}, onErrorGetDir);
dirEntry.getDirectory('photos', { create: true }, function (subDirEntry) {
}, onErrorGetDir);
},onErrorGetDir)
},errorCallback)
}
//資料夾建立失敗回撥
function onErrorGetDir(error){
console.log("資料夾建立失敗!")
}
function errorCallback(e) {
console.log(e.toString());
alert(e.toString());
}
2.在指定的資料夾中寫檔案
在表型採集模版與資料/data資料夾中寫入檔案
function saveAs(obj,tempName,fileName) {//當然可以自定義簡單的下載檔案實現方式
var dirUri = cordova.file.externalRootDirectory;
window.resolveLocalFileSystemURI(dirUri,function (Entry) {
Entry.getDirectory("表型採集模版與資料", {
create: true,
},function (dirEntry) {
dirEntry.getDirectory('data', { create: true }, function (subDirEntry) {
savefile(subDirEntry,obj,fileName);
}, onErrorGetDir);
},onErrorGetDir)
})
}
function savefile(dirEntry,fileData, fileName){
dirEntry.getFile(
fileName, {
create: true,
exclusive: false
},
function (fileEntry) {
writeFile(fileEntry, fileData);
}, onErrorCreateFile);
}
function writeFile(fileEntry, dataObj) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function () {
};
fileWriter.onwrite=function () {
alert('匯出成功!')
}
fileWriter.onerror = function (e) {
console.log('Failed file write: ' + e.toString());
};
fileWriter.write(dataObj);
});
}
function onErrorCreateFile(e) {
console.log('Failed create file: ' + e.toString());
};
function onErrorGetDir(error){
console.log("資料夾建立失敗!")
}
三、效果