javascript - Phonegap - 如何访问 www 文件夹中的文件?

标签 javascript ios cordova file-access

我看到了多种如何访问 www 文件夹中的文件的解决方案,但没有一种解决方案适合我。我使用 iOS 模拟器测试 iOS 下的应用程序。
我想访问 www 文件夹中的文件 test.txt

我目前的解决方案是这样的:

var filePathURI = getPhoneGapPath() + "test.txt";
window.resolveLocalFileSystemURI(filePathURI, onResolveSuccess, onFail);

function getPhoneGapPath() {  
    'use strict';
    var path = window.location.pathname;
    var phoneGapPath = path.substring(0, path.lastIndexOf('/') + 1);
    return phoneGapPath;
};

此解决方案对我不起作用。 errorCode = 2 出现错误,这显然意味着 FileError.SECURITY_ERR。但是我尝试使用 resolveLocalFileSystemURI 我无法访问该文件。

信息:我尝试遵循 filePathURI:

  1. /Users/UserName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/GUID/AppName.app/www/test.txt
  2. file:///Users/UserName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/GUID/AppName.app/www/test.txt

谁能给我一个可行的解决方案?

最佳答案

我建议使用 PhoneGap 的文件插件提供的 resolveLocalFileSystemURL 方法。然后,您可以使用 cordova.file.applicationDirectory 属性访问您的 www 文件夹所在的位置。

确保安装插件:$ cordova plugin add org.apache.cordova.file

然后您可以使用如下对象来解析文件并执行所需的任何操作:

var FileManager = {

  /**
   * Execute this.entryHandler against all files and directories in phonegap's www folder
   */
  run: function () {

    window.resolveLocalFileSystemURL(
      cordova.file.applicationDirectory + 'www/',
      this.directoryFoundHandler,
      this.errorHandler
    );

  },

  /**
   * The directory has been successfully read.  Now read the entries.
   *
   * @param {DirectoryEntry} directoryEntry
   */
  directoryFoundHandler: function (directoryEntry) {

    var directoryReader = directoryEntry.createReader();

    directoryReader.readEntries(
      this.entryHandler,
      this.errorHandler
    );

  },

  /**
   * Files were successfully found.  Parse them!
   *
   * @param {Array.<FileEntry>} entries
   */
  entryHandler: function (entries) {

    entries.forEach(function (entry) {

      // Deal with your files here
      if (entry.isDirectory) {
        // It's a directory might need to loop through again
      } else {
        // It's a file, do something
      }

    });

  },


  /**
   * @param {FileError} error
   */
  errorHandler: function (error) {

    console.log("ERROR", error);

  }

};

关于javascript - Phonegap - 如何访问 www 文件夹中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21880109/

相关文章:

javascript - Svg 线未显示在谷歌图表上?

javascript - Math.sin() .cos() 的成本 vs 怪异的自己的实现

java - CordovaWebView 与 android 中的 onBackPressed 方法混淆

javascript - 将 PDF 附加到 ionic 中的电子邮件编辑器

ios - Swift:为可选值创建一个中缀运算符,当空时提供默认值

ios - 放大缩小 iOS 版 phoneGap

javascript - 一个网页拥有 1 个 ng-app,还是多个网页共享同一个 ng-app?

javascript - Cytoscape,如何突出显示点击的边缘?

ios - 如何同步移动标记和相机并始终将标记放置在相机位置IOS的中心

ios - 新的 iOS iPhoto 帮助控件是标准类吗?