Ionic

How To Read A File In A Cordova App

Posted by Weston Ganger on November 03, 2016

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:


Posted in Ionic and Tagged with cordova ionic file 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts