Search code examples
javascriptangularjsangularjs-formsangularjs-fileupload

How to get file content and other details in AngularJS


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>


Solution

  • I have used a directive to handle file in forms (as suggested by joakimbl in the answer here):

    app.directive('validFile',[function() {
      return {
        require : 'ngModel',
        scope : {format: '@', upload : '&upload'},
        link : function(scope, el, attrs, ngModel) {
          // change event is fired when file is selected
          el.bind('change', function(event) {
            console.log(event.target.files[0]);
            scope.upload({file:event.target.files[0]});
            scope.$apply(function() {
              ngModel.$setViewValue(el.val());
              ngModel.$render();
            });
          })
        }
      }
    }]);
    

    in your HTML

    <input type="file" valid-file upload="uploadFile(file)" ng-model="file">
    

    Here uploadFile will be a function in your controller where you can get contetnts of file

    Controller code

    $scope.uploadFile = function(element) {
        $scope.user.file = element;
        console.log($scope.user);
      }
    

    please have a look at this plunker