【问题标题】:How to create a separate directory for cordova app and storing data in it?如何为cordova应用程序创建一个单独的目录并在其中存储数据?
【发布时间】:2016-01-28 08:37:06
【问题描述】:

我想为我的 cordova 项目创建一个特定的目录。我不知道该怎么做。 我提到了这样的链接, How to move file to app directory cordova

cordova, android app how to create subfolder 和其他一些链接。 但尚不清楚他们是否为此使用了任何cordova插件,或者我们可以使用纯javascript。这些对我不起作用。 请建议是否有可用的插件或功能。

谢谢。

【问题讨论】:

  • 尝试显示一些代码

标签: javascript jquery cordova jquery-mobile cordova-plugins


【解决方案1】:

你需要使用这个插件:https://www.npmjs.com/package/cordova-plugin-file

我不知道您使用的是什么版本的cordova,以及这个插件是否已更新,但是当我使用它时,它不适用于WindowsPhone。适用于 Android 和 iOS。

获取文件系统:

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

下载文件功能:

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

创建目录:

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

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

onDirectorySuccessonDirectoryFail 是这样的函数:

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

获取目录中文件的路径:

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

获取文件:

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

要先删除一个文件,你需要得到它:

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

然后在成功函数中:

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

我的应用程序正在下载文件,所以这是将文件保存在目录中的代码:

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

这不是你的情况,但我希望它有所帮助。

【讨论】:

  • 是的。我读过它。但是文档有点混乱。
  • 那些目录已经创建了吗?以及如何将文件写入该目录?
  • 出现错误,即LocalFileSystemundefined
  • 在那一行之前我有这段代码window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;。也许可以解决。您是否正确导入了插件?
  • 很好,但现在 fileSystem 未定义。
猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
相关资源
最近更新 更多