requestFileSystem() vs resolveLocalFileSystemURL()


.

When you get file system access using requestFileSystem, access is granted for the sandboxed file system only (the sandbox limits access to the app itself), not for general access to any file system location on the device. (read here for TEMPORARY and here for PERSISTENT storage tutorial)

To access file system locations outside the sandboxed storage, use other methods such as window.requestLocalFileSystemURL, which support platform-specific locations. 

As of Cordova v1.2.0 (cordova-plugin-file), URLs to important file-system directories are provided. Each URL is in the form file:///path/to/spot/, and can be converted to a DirectoryEntry using window.resolveLocalFileSystemURL(). (read here)
.

Methods

requestFileSystem()

Requests a file system where data should be stored. You access a sandboxed file system by requesting a LocalFileSystem object using this global method, window.requestFileSystem().
void requestFileSystem(
  in unsigned short type, 
  in unsigned long long size, 
  in FileSystemCallback successCallback, 
  in ErrorCallback errorCallback
);
Parameters
type
The storage type of the file system. The values can be either TEMPORARY or PERSISTENT.
size
The storage space—in bytes—that you need for your app.
successCallback
The success callback that is called when the browser provides a file system. Its argument is the FileSystem object with two properties:
  • name - the unique name assigned by the browser to the file system.
  • root - the read-only DirectoryEntry object representing the root of the file system.
opt_errorCallback
The error callback that is called when errors happen or when the request to obtain the file system is denied. Its argument is the FileError object.
Returns
void
Exceptions
This method can raise an FileError with the following code:
ExceptionDescription
SECURITY_ERRORThe application does not have permission to access the file system interface. For example, you cannot run from file://. For more details, see the article on basic concepts.

resolveLocalFileSystemURL()

Lets you look up the entry for a file or directory with a local URL.
void resolveLocalFileSystemURL(
  in DOMString url, 
  in EntryCallback successCallback, 
  in optional ErrorCallback errorCallback
);
Parameters
url
The URL of a local file in the file system.
successCallback
The success callback that is called when the browser provides the file or directory for the supplied URL.
errorCallback
The error callback that is called when errors happen or when the request to obtain the entry object is denied.
Returns
void
Exceptions
This method can raise an FileError with the following code:
ExceptionDescription
ENCODING_ERRThe syntax of the URL was invalid.
NOT_FOUND_ERRThe URL was structurally correct, but refers to a resource that does not exist.
SECURITY_ERRThe application does not have permission to access the file system interface.

.
REFERENCE:
1. https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html
2. https://developer.mozilla.org/en-US/docs/Web/API/LocalFileSystem
.

0 Comments:

Ionic 1 Cordova Files (persistent)


Objective

1. To use window.requestFileSystem
2. To use window.PERSISTENT type of storage
3. To implement file create, read, write and delete.

References


0. Add Cordova

cordova plugin add cordova-plugin-file


1. HTML View

<button ng-click="cdv('create-file')" class="button button-positive button-block">create-file</button>

<button ng-click="cdv('write-file')" class="button button-positive button-block">write-file</button>

<button ng-click="cdv('read-file')" class="button button-positive button-block">read-file</button>

<button ng-click="cdv('remove-file')" class="button button-positive button-block">remove-file</button>

2. JS Controller

// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams,$ionicPlatform) {

$scope.cdvTasks = function (options) {
    console.log('cdvTasks begin');
   $ionicPlatform.ready(function() {
    console.log('deviceReady');
    /*cordova task begin*/
    switch (options) {
        case "create-file":
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, successCallback1, errorCallback1)

            function successCallback1(fs) {
                fs.root.getFile('log.txt', {
                    create: true,
                    exclusive: true
                }, function(fileEntry) {
                    alert('File creation successfull!')
                }, errorCallback1);
            }

            function errorCallback1(error) {
                alert("ERROR: " + error.code)
            }
            break;
        case "write-file":
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, successCallback2, errorCallback2)

            function successCallback2(fs) {
                fs.root.getFile('log.txt', {
                    create: true
                }, function(fileEntry) {

                    fileEntry.createWriter(function(fileWriter) {
                        fileWriter.onwriteend = function(e) {
                            alert('Write completed.');
                        };

                        fileWriter.onerror = function(e) {
                            alert('Write failed: ' + e.toString());
                        };

                        var blob = new Blob(['Lorem Ipsum'], {
                            type: 'text/plain'
                        });
                        fileWriter.write(blob);
                    }, errorCallback2);
                }, errorCallback2);
            }

            function errorCallback2(error) {
                alert("ERROR: " + error.code)
            }

            break;
        case "read-file":
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, successCallback3, errorCallback3)

            function successCallback3(fs) {
                fs.root.getFile('log.txt', {}, function(fileEntry) {

                    fileEntry.file(function(file) {
                        var reader = new FileReader();

                        reader.onloadend = function(e) {
                         
                            alert(this.result);
                        };
                        reader.readAsText(file);
                    }, errorCallback3);
                }, errorCallback3);
            }

            function errorCallback3(error) {
                alert("ERROR: " + error.code)
            }

            break;
        case "remove-file":
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, successCallback4, errorCallback4)

            function successCallback4(fs) {
                fs.root.getFile('log.txt', {
                    create: false
                }, function(fileEntry) {

                    fileEntry.remove(function() {
                        alert('File removed.');
                    }, errorCallback4);
                }, errorCallback4);
            }

            function errorCallback4(error) {
                alert("ERROR: " + error.code)
            }


            break;
    } /*switch*/
    function cdvFail(error) {
        alert("ERROR: " + error.code)
    }       
        /*cordova task end*/
});/*device ready*/
}/*app task*/ 

}

0 Comments:

Ionic 1 Cordova Files (temporary)


Objective

1. To use window.requestFileSystem
2. To use window.TEMPORARY type of storage
3. To implement file create, read, write and delete.

References

0. Add Cordova

cordova plugin add cordova-plugin-file


1. HTML View

<button ng-click="cdv('create-file')" class="button button-positive button-block">create-file</button>

<button ng-click="cdv('write-file')" class="button button-positive button-block">write-file</button>

<button ng-click="cdv('read-file')" class="button button-positive button-block">read-file</button>

<button ng-click="cdv('remove-file')" class="button button-positive button-block">remove-file</button>

2. JS Controller


function ($scope, $stateParams,$ionicPlatform) {

$scope.cdv = function (options) {
    console.log('cordova plugins');
   $ionicPlatform.ready(function() { 
    console.log('deviceReady');
    /*cordova task begin*/
    switch (options) {
        case "create-file":
            var type1 = window.TEMPORARY;
            var size1 = 5 * 1024 * 1024;
            window.requestFileSystem(type1, size1, successCallback1, errorCallback1)

            function successCallback1(fs) {
                fs.root.getFile('log.txt', {
                    create: true,
                    exclusive: true
                }, function(fileEntry) {
                    alert('File creation successfull!')
                }, errorCallback1);
            }

            function errorCallback1(error) {
                alert("ERROR: " + error.code)
            }
            break;
        case "write-file":
            var type2 = window.TEMPORARY;
            var size2 = 5 * 1024 * 1024;
            window.requestFileSystem(type2, size2, successCallback2, errorCallback2)

            function successCallback2(fs) {
                fs.root.getFile('log.txt', {
                    create: true
                }, function(fileEntry) {

                    fileEntry.createWriter(function(fileWriter) {
                        fileWriter.onwriteend = function(e) {
                            alert('Write completed.');
                        };

                        fileWriter.onerror = function(e) {
                            alert('Write failed: ' + e.toString());
                        };

                        var blob = new Blob(['Lorem Ipsum'], {
                            type: 'text/plain'
                        });
                        fileWriter.write(blob);
                    }, errorCallback2);
                }, errorCallback2);
            }

            function errorCallback2(error) {
                alert("ERROR: " + error.code)
            }

            break;
        case "read-file":
            var type3 = window.TEMPORARY;
            var size3 = 5 * 1024 * 1024;
            window.requestFileSystem(type3, size3, successCallback3, errorCallback3)

            function successCallback3(fs) {
                fs.root.getFile('log.txt', {}, function(fileEntry) {

                    fileEntry.file(function(file) {
                        var reader = new FileReader();

                        reader.onloadend = function(e) {
                            
                            alert(this.result);
                        };
                        reader.readAsText(file);
                    }, errorCallback3);
                }, errorCallback3);
            }

            function errorCallback3(error) {
                alert("ERROR: " + error.code)
            }

            break;
        case "remove-file":

            var type = window.TEMPORARY;
            var size = 5 * 1024 * 1024;
            window.requestFileSystem(type, size, successCallback4, errorCallback4)

            function successCallback4(fs) {
                fs.root.getFile('log.txt', {
                    create: false
                }, function(fileEntry) {

                    fileEntry.remove(function() {
                        alert('File removed.');
                    }, errorCallback4);
                }, errorCallback4);
            }

            function errorCallback4(error) {
                alert("ERROR: " + error.code)
            }


            break;
    } /*switch*/
    function cdvFail(error) {
        alert("ERROR: " + error.code)
    }         
        /*cordova task end*/
});/*device ready*/
}/*app task*/    

}


NOTE:

List of Error Codes and Meanings

When an error is thrown, one of the following codes will be used.

CodeConstant
1NOT_FOUND_ERR
2SECURITY_ERR
3ABORT_ERR
4NOT_READABLE_ERR
5ENCODING_ERR
6NO_MODIFICATION_ALLOWED_ERR
7INVALID_STATE_ERR
8SYNTAX_ERR
9INVALID_MODIFICATION_ERR
10QUOTA_EXCEEDED_ERR
11TYPE_MISMATCH_ERR
12PATH_EXISTS_ERR

0 Comments:

Ionic 1 Cordova Camera





0. Add Cordova





cordova plugin add cordova-plugin-camera

1. HTML



<button class = "button" ng-click = "takePicture()">
Take Picture</button>
<button class = "button" ng-click = "takePictureResize()">
Take Picture (Resize)</button>
<button class = "button" ng-click = "openPicture()">
Open Gallery</button>
<img ng-src = "{{mediafile}}">

2.JS


function($scope, $stateParams) {
    $scope.mediafile = '';
    var options = {};
    /*options
    quality: 50,
    destinationType: 1, 
    //0=DATA_URL, 1=FILE_URI, 2=NATIVE_URI
    //https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html#cameradestinationtype--enum
    sourceType: 1,
    //0=PHOTOLIBRARY, 1=CAMERA 2=SAVEDPHOTOALBUM
    //https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html#camerapicturesourcetype--enum
    encodingType: 0,
    //0=JPEG 1=PNG
    mediaType: 0,
    //0=PICTURE, 1=VIDEO, 2=ALLMEDIA
    //https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html#cameramediatype--enum
    allowEdit: true,
    //Allow simple editing of image before selection.
    correctOrientation: true //Corrects Android orientation quirks 
    Note: If you want to use ENUM instead of NUMBERS, set options in DeviceReady event.
    */

    var initOptions = function() {
        options = {
            quality: 50,
            destinationType: 1,
            sourceType: 1,
            encodingType: 0,
            mediaType: 0,
            allowEdit: true,
            correctOrientation: true
        }
    }
    $scope.takePicture = function() {
        initOptions();
        cdvGetPicture(options);
    };
    $scope.takePictureResize = function() {
        initOptions();
        options.targetWidth = 200;
        options.targetWidth = 200;
        cdvGetPicture(options);
    };
    $scope.openPicture = function() {
        initOptions();
        options.sourceType = 0;
        cdvGetPicture(options);
    };
    var cdvGetPicture = function(options) {
        console.log('begin getPicture');
        document.addEventListener("deviceready", function() {
            console.log('deviceReady');
            /*cordova task begin*/
            navigator.camera.getPicture(function cameraSuccess(imageUri) {
                console.log(imageUri);
                $scope.mediafile = imageUri;
                $scope.$apply();
                // You may choose to copy the picture, save it somewhere, or upload.
                //createFileEntry(imageUri);
            }, function cameraError(error) {
                console.debug("Unable to obtain picture: " + error, "app");
            }, options);
            /*cordova task end*/
        }); /*device ready*/
    } /*app task*/
}

0 Comments:

Ionic 1 Call Cordova Plug Ins


1. HTML


<button class = "button" ng-click = "callCordova()">
Call Cordova Plug In</button>


2.JS

function($scope, $stateParams) {



    var cdv = function(options) {

        console.log('begin cdv');

        document.addEventListener("deviceready", function() {

            console.log('deviceReady');

            /*cordova task begin*/




            /*cordova task end*/

        }); /*device ready*/

    } /*cdv*/

}/*controller*/

0 Comments:

Apps Scripts Upload File To Google Drive

1.Code.gs


function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function doPost(e) {

  if (!e.parameters.filename || !e.parameters.file || !e.parameters.fileformat) {

    return message("Error: Bad parameters");
  } else {
    var mime =e.parameters.fileformat;
    if (mime) {
      var data = Utilities.base64Decode(e.parameters.file, Utilities.Charset.UTF_8);
      var blob = Utilities.newBlob(data, mime, e.parameters.filename);
      DriveApp.getFolderById('0B86b-ALn-1MGTEI1MjJ4SWFxSDQ').createFile(blob);
      return message("completed");
    } else {
      return message("Error: Bad image format");
    }
  }
}

function message(msg) {
  return ContentService.createTextOutput(JSON.stringify({result: msg})).setMimeType(ContentService.MimeType.JSON);
}


2.Index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <meta charset="UTF-8">

    <script src="https://code.jquery.com/jquery.min.js"></script>
  </head>
<body>
    <input type="file" id="file">

    <script type="text/javascript">
        $(function(){
          var projectid="AKfycbypZxDkD2Br3dXDTieD2zWS2lvqvn5Ur7gY52ivcNg_TdK8a2V8";
            var url = 'https://script.google.com/macros/s/'+projectid+'/exec';
            var params = {
                filename: 'test',
                fileformat: 'txt'
            };

            $('#file').on("change", function() {
                var file = this.files[0];
              //console.dir(file);
              /*example
              lastModified:1491349967000
              lastModifiedDate:Wed Apr 05 2017 07:52:47 GMT+0800 (MYT)
              name:"43e4af3c-36a5-47bf-bfec-658504d9de33.mp4"
              size:67755
              type:"video/mp4"
              webkitRelativePath:""
              */
              
                var fr = new FileReader();
                fr.onload = function(e) {
                    params.file = e.target.result.replace(/^.*,/, '');
                  params.filename=file.name.split('.')[0];
                  params.fileformat=file.type;
                    postJump();
                }
                fr.readAsDataURL(file);
            });

            function postJump(){
                var html = '<form method="post" action="'+url+'" id="postjump" style="display: none;">';
                Object.keys(params).forEach(function (key) {
                    html += '<input type="hidden" name="'+key+'" value="'+params[key]+'" >';
                });
                html += '</form>';
                $("body").append(html);
                $('#postjump').submit();
                $('#postjump').remove();
            }
        });
    </script>
</body>
</html>

Reference:

0 Comments: