Phonegap - How to access a file in a www folder?

I saw several solutions on how to access the file in the www folder, but the solution does not work for me. I am testing an application for iOS using an iOS simulator.
I want to access the file test.txtin the www folder.

My current solution looks like this:

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;
};

This solution does not work for me. I am getting an error with errorCode = 2, which obviously means FileError.SECURITY_ERR. However, I try, with resolveLocalFileSystemURII cannot access the file.

INFO: I tried to follow 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

- ?

+2
5

resolveLocalFileSystemURL, PhoneGap. cordova.file.applicationDirectory www.

, : $ cordova plugin add org.apache.cordova.file

, , :

var FileManager = {

  /**
   * Execute this.entryHandler against all files and directories in phonegap 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 a directory might need to loop through again
      } else {
        // It a file, do something
      }

    });

  },


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

    console.log("ERROR", error);

  }

};
+2

ajax, ...

$.get( "test.txt", function( data ) {
  console.log( "Load was performed.", data );
});

, → config.xml

<feature name="http://api.phonegap.com/1.0/file" />

0

, . , . .

.

app_FileSystem - , GetAppFS

FS ajax getjson . .

: http://docs.phonegap.com/en/3.3.0/cordova_file_file.md.html#LocalFileSystem

app_FileSystem.root.fullPath; // Get the app file system root full path

function GetAppFS ()
{
    var self = this;
   self.state = "";                     // store the state of the process for debuggin purposes
   self.fileSystem = {};

    window.requestFileSystem ( LocalFileSystem.PERSISTENT, 0, getFileSystemSuccess, dispatchFailure );

    /**
     *
     * Called when we receive a valid file system. Once we do that, we need to ask for all
     * the documents within the file system.
     *
     */
    function getFileSystemSuccess ( fileSystem )
    {
        self.state = "Received File System";
         self.fileSystem = fileSystem;
        app_FileSystem = fileSystem;
         OnFSReady ();
    };

    /**
     *
     * All our functions need a failure callback, so we provide dispatchFailure. If an error occurs, we'll
     * at least log it to the console, and then call the failure function attached to self.failure(), if any.
     *
     */
    function dispatchFailure ( e )
    {
        // some sort of failure :-(
        console.log ("While " + self.state + ", encountered error: " + JSON.stringify(e));
         alert ("dev FS ERROR ");
    };  
};
0

, jQuery, , .

: www Cordova/Phone Gap Android , :

  • .apk, . Android .apk .
  • Cordova File.

Android- , , URI "" , '/android_asset/' , Android. ( iOS, .)

, , XMLHttpRequest , , www, . ( , .)

, - www "www/":

var readFileInWWWFolder = function(filename, onSuccess, onFailure){

    var request = new XMLHttpRequest();

    request.onload = function() {

        var arrayBuffer = request.response;

        if (arrayBuffer) {

            onSuccess(new Uint8Array(arrayBuffer));
        }
        else {

            onFailure();
        }
    };

    request.open("GET", filename, true);
    request.responseType = "arraybuffer";
    request.send();
};

Cordova 4.3.0 Android 4.4.2 (Kitkat).

0

, , - fs.download www- Cordovas. original .

-, :

  • npm install cordova-promise-fs
  • cordova plugin add cordova-plugin-file --save
  • cordova plugin add cordova-plugin-file-transfer --save

:

import CordovaPromiseFS from 'cordova-promise-fs'

const fs = CordovaPromiseFS({
  persistent: true,
  storageSize: 200 * 1024 * 1024,
  concurrency: 3
})

If you use React, the above must be declared before the component is created Class, and the lower code must be in its own function inside the component Class. See the GitHub comment for more details .

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)
  }
)
0
source

All Articles