Thursday, January 29, 2015

PhoneGap plugins: writing file

file plugin needed.
Install it with this: 

phonegap plugin add org.apache.cordova.file

Here is my example.html(within javascript code).
This example provides to write file in locale storage:

<!DOCTYPE html>
<html>
  <head>
    <title>PhoneGap Write File Example Page</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        fileSystem.root.getFile("writing_test_with_phonegap.txt", {create: true, exclusive: false}, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwriteend = function(evt) {
            console.log("contents of file now 'some sample text'");
            writer.truncate(11);
            writer.onwriteend = function(evt) {
                console.log("contents of file now 'some sample'");
                writer.seek(4);
                writer.write(" different text");
                writer.onwriteend = function(evt){
                    console.log("contents of file now 'some different text'");
                }
            };
        };
        writer.write("some sample text");
        alert("file written!!!");
    }

    function fail(error) {
        console.log(error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Write File</p>
  </body>
</html>


Bye...

No comments:

Post a Comment