How to create a separate directory for cordova app and storing data in it?

半世苍凉 提交于 2019-12-05 14:17:09

You need to use this plugin: https://www.npmjs.com/package/cordova-plugin-file

I don't know what version of cordova do you use and if this plugin was updated, but when I use it, it doesn't work with WindowsPhone. Ok for Android and iOS.

To get file system:

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, downloadFile, fileSystemFail);

Donwload file function:

downloadFile: function(fileSystem){
    // your code
}

To create a directory:

var directoryEntry = fileSystem.root;
var folderName = "Folder";

directoryEntry.getDirectory(folderName, { create: true, exclusive: false }, onDirectorySuccess, onDirectoryFail);

Where onDirectorySuccess and onDirectoryFail are functions like:

onDirectorySuccess: function(parent){
    console.log(parent);
},
onDirectoryFail: function(error){
    console.log("Unable to create new directory: " + error.code);
}

To get path of file in the directory:

var filePath = directoryEntry.toURL() + "/" + folderName + "/" + fileName;

And to get file:

directoryEntry.getFile(folderName + "/" + fileName, { create: true, exclusive: false }, onFileSuccess, onFileFail);

To delete a file first you need to get it:

directoryEntry.getFile(folderName + "/" + fileName, { create: true, exclusive: false }, onFileSuccessRemove, onFileFail);

Then in success function:

function onFileSuccessRemove(entry) {
    entry.remove();
}

My application was with file download, so this is code to save a file in a directory:

var fileTransfer = new FileTransfer();
fileTransfer.download(URL, filePath, downloadComplete, downloadFail, true);

It's not your case but I hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!