Read A File In A Cordova App

Posted By Weston Ganger

Heres how to read a file from a Cordova app such as a file upload or something. I will show you how to do it using plain javascript or using AngularJS 1.x because it has a weird file input quirks.

Plain Javascript / Cordova


<input type="file" onchange="readFile(this.files)" />

window.readFile = function(files){
  var file = files[0];
  var reader = new FileReader();
  reader.onload = function(e) {
    // This gets called after using one of the read functions below
    console.log(e.target.result);
  };

  // Option 1: Read as text
  reader.readAsText(file);

  // Option 2: Read as Data URL
  reader.readAsDataURL(file)
};


AngularJS 1.x / Ionic 1.x


<input type="file" onchange="angular.element(this).scope().setFiles(this.files)" />

.controller("MyCtrl", function($scope){
  $scope.readFile = function(files){
    var file = files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      // This gets called after using one of the read functions below
      console.log(e.target.result);
    };
  
    // Option 1: Read as text
    reader.readAsText(file);
  
    // Option 2: Read as Data URL
    reader.readAsDataURL(file)
  };
})


Related External Links:

Article Topic:Software Development - Ionic

Date:November 03, 2016