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

Javascript Phonegap-如何访问www文件夹中的文件?,javascript,ios,cordova,file-access,Javascript,Ios,Cordova,File Access,我看到了多种解决方案如何访问www文件夹中的文件,但没有一种解决方案适合我。我使用iOS模拟器在iOS下测试应用程序 我想访问www文件夹中的文件test.txt 我当前的解决方案如下所示: var filePathURI = getPhoneGapPath() + "test.txt"; window.resolveLocalFileSystemURI(filePathURI, onResolveSuccess, onFail); function getPhoneGapPath() {

我看到了多种解决方案如何访问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\u ERR
。但是,我尝试使用
resolveLocalFileSystemURI
无法访问该文件。

信息:我尝试了以下
filePathURI

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

  • 有人能给我一个可行的解决方案吗?

    我用ajax加载语言文件,如下所示

    $.get( "test.txt", function( data ) {
      console.log( "Load was performed.", data );
    });
    
    我认为对于您的解决方案,您必须向应用程序-->config.xml添加读取权限


    试试这个,我的部分功能。首先需要获取文件系统,然后获取根路径。修改它以满足您的需要

    您只需执行以下操作即可

    app_FileSystem for me是一个全局变量,由GetAppFS分配

    在获得FS和根路径之后,您可以简单地使用ajax调用或带有适当数据类型集的getjson调用。它对我有用

    同时检查文档,这很有帮助:


    我建议使用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);
    
      }
    
    };
    
    var文件管理器={
    /**
    *对phonegap的www文件夹中的所有文件和目录执行this.entryHandler
    */
    运行:函数(){
    window.resolveLocalFileSystemURL(
    cordova.file.applicationDirectory+“www/”,
    这是directoryFoundHandler,
    这是错误处理程序
    );
    },
    /**
    *已成功读取目录。现在读取条目。
    *
    *@param{DirectoryEntry}DirectoryEntry
    */
    directoryFoundHandler:函数(directoryEntry){
    var directoryReader=directoryEntry.createReader();
    directoryReader.readEntries(
    这是entryHandler,
    这是错误处理程序
    );
    },
    /**
    *已成功找到文件。请解析它们!
    *
    *@param{Array.}项
    */
    entryHandler:函数(条目){
    entries.forEach(函数(entry){
    //在这里处理你的文件
    if(条目.isDirectory){
    //这是一个可能需要再次循环的目录
    }否则{
    //这是一个文件,做点什么吧
    }
    });
    },
    /**
    *@param{FileError}错误
    */
    errorHandler:函数(错误){
    console.log(“错误”,ERROR);
    }
    };
    
    由于我刚刚遇到了同样的问题,但不想使用jQuery,我想我也在这里发布了我的解决方案

    但在此之前,请注意:Cordova/Phone Gap的www文件夹中的文件作为所谓的资产存储在Android world中,这意味着:

    • 它们是.apk分发文件的一部分,该文件是一个压缩归档文件。Android直接从这个.apk文件中读取文件,并且不在本地文件系统中单独存储这些文件
    • 因此,这些文件是只读的,不能通过Cordova文件插件访问
    如果你深入研究,你会发现Cordova用一个“文件”方案过滤所有URI,该方案的路径以“/android_asset/”开头,并使用android的资产访问功能专门处理它们。(如果能从iOS专家那里听到Cordova在他们的世界里是如何处理的,那将是一件有趣的事情。)

    这意味着,如果需要访问文件内容,使用XMLHttpRequest可能是访问www文件夹文件的唯一可移植方式。(如果您只需要某些系统函数的文件路径,其他方法也可以使用。)

    以下是代码,filename是www文件夹中的路径,没有“www/”前缀:


    这已经用Cordova 4.3.0和Android 4.4.2(Kitkat)进行了测试。

    一个有效的技巧是
    fs。将www文件夹中的每个文件下载到Cordova的持久文件系统。请参阅我的

    首先,在终端:

  • npm安装cordova promise fs
  • cordova插件添加cordova插件文件——保存
  • cordova插件添加cordova插件文件传输——保存
  • 然后,在前端:

    import CordovaPromiseFS from 'cordova-promise-fs'
    
    const fs = CordovaPromiseFS({
      persistent: true,
      storageSize: 200 * 1024 * 1024,
      concurrency: 3
    })
    
    如果使用React,则必须在创建组件
    之前声明上面的代码,而下面的代码应该在组件
    中具有自己的功能。有关更多详细信息,请参阅我的

    window.resolveLocalFileSystemURL(
      cordova.file.applicationDirectory + 'www/epubs/alice.epub',
        // If successful...
        (fileSystem) => {
          const downloadUrl = fileSystem.toURL()
          const localUrl = 'alice.epub' // the filename it is stored as in the device
          fs.download(
            downloadUrl,
            localUrl,
            (progressEvent) => {
              if (progressEvent.loaded && progressEvent.total) {
              console.log('progress', Math.round((progressEvent.loaded / progressEvent.total) * 100))
            }
          }
        ).then((filedata) => {
          return fs.toInternalURL(localUrl)
        })
        .then((localPath) => {
          this.setState({ epubPath: localPath })
        }).catch((error) => {
          console.log('some error happend', error)
        })
      },
      // If unsuccessful
      (err) => {
        console.log(err)
      }
    )
    

    通过ajax调用,我可以访问文件的内容,但我需要一个带有“resolveLocalFileSystemURI”方法的“FileEnty”对象……我添加了该功能,但仍然出现安全错误……看起来我确实没有访问该文件的权限。它在iphone应用程序中是否也能以同样的方式工作?
    import CordovaPromiseFS from 'cordova-promise-fs'
    
    const fs = CordovaPromiseFS({
      persistent: true,
      storageSize: 200 * 1024 * 1024,
      concurrency: 3
    })
    
    window.resolveLocalFileSystemURL(
      cordova.file.applicationDirectory + 'www/epubs/alice.epub',
        // If successful...
        (fileSystem) => {
          const downloadUrl = fileSystem.toURL()
          const localUrl = 'alice.epub' // the filename it is stored as in the device
          fs.download(
            downloadUrl,
            localUrl,
            (progressEvent) => {
              if (progressEvent.loaded && progressEvent.total) {
              console.log('progress', Math.round((progressEvent.loaded / progressEvent.total) * 100))
            }
          }
        ).then((filedata) => {
          return fs.toInternalURL(localUrl)
        })
        .then((localPath) => {
          this.setState({ epubPath: localPath })
        }).catch((error) => {
          console.log('some error happend', error)
        })
      },
      // If unsuccessful
      (err) => {
        console.log(err)
      }
    )