How to get file content and other details in AngularJS

Mohammed picture Mohammed · Feb 14, 2017 · Viewed 21.5k times · Source

How can I get file content while I click on submit button. I'm getting only first and second input. Please refer to snippet:

!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <input type="file" ng-model="user.file">
    <br><br>
    <button ng-click="reset()">Submit</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>
  <script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
   $scope.reset = function(){
   console.log($scope.user)
   }
   
});
</script>

</body>
</html>

Answer

lin picture lin · Feb 14, 2017

You can't access the file content directly by using ng-scopes but you are able to read the file content with native JavaScript FileAPI. Here is a working fiddle. I think you want to display the file content without uploading them on server side. It's not 100% clear what you want so thats how you can get the filecontent, filesize and filename in browser without uploading.

View

<div ng-controller="MyCtrl">
  <input type="file" id="myFileInput" />
  <br /><br />
  <button ng-click="submit()">
    Submit
  </button>
  <br /><br />
  <br /><br />
  <h1>
    Filename: {{ fileName }}
  </h1>
  <h2>
    File size: {{ fileSize }} Bytes
  </h2>
  <h2>
    File Content: {{ fileContent }}
  </h2>
</div>

AngularJS App

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.fileContent = '';
    $scope.fileSize = 0;
    $scope.fileName = '';
    $scope.submit = function () {
      var file = document.getElementById("myFileInput").files[0];
      if (file) {
        var aReader = new FileReader();
        aReader.readAsText(file, "UTF-8");
        aReader.onload = function (evt) {
            $scope.fileContent = aReader.result;
            $scope.fileName = document.getElementById("myFileInput").files[0].name;
            $scope.fileSize = document.getElementById("myFileInput").files[0].size;;
        }
        aReader.onerror = function (evt) {
            $scope.fileContent = "error";
        }
      }
    }
});