How to get file content and other details in AngularJS [duplicate]
Asked Answered
M

2

6

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>
Malia answered 14/2, 2017 at 12:54 Comment(2)
Do you want to read the file contents?Scintillator
yes on console, I want to get file info like i m getting firstname and lastnme. @GangadharJannuMalia
C
2

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

Casemaker answered 14/2, 2017 at 13:19 Comment(8)
Any other way without directive. @nishantagrawalMalia
I think he dont want to upload the file. He just want to get the file content.Hemiplegia
I just want to send the file details to backend, so just for testing purpose, I console the data that is going in backend, I found that -> { "firstName": "dd", "lastName": "dd" } but file content missing. One way of doing is using Directives. I want to know is this possible without Directive? @HemiplegiaMalia
@Malia my solution doesnt work with directives. So the answer is yes. What are you missing?Hemiplegia
Thanks for that but cant this possible in pure AngularJS instead of using JS part?@HemiplegiaMalia
@Malia Not possible, thats why I did not deliver you a answer which uses AngularJS core directives.Hemiplegia
How can I use the valid-file-upload only after click of submit button, currently what happening is while I upload the file it sends the data, I want that think on click of submit button alongwith form data this file data should go. @HemiplegiaMalia
@Malia i dont know. This is not my answer but you marked it as the right one. My answer is the other one.Hemiplegia
H
6

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";
        }
      }
    }
});
Hemiplegia answered 14/2, 2017 at 13:22 Comment(0)
C
2

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

Casemaker answered 14/2, 2017 at 13:19 Comment(8)
Any other way without directive. @nishantagrawalMalia
I think he dont want to upload the file. He just want to get the file content.Hemiplegia
I just want to send the file details to backend, so just for testing purpose, I console the data that is going in backend, I found that -> { "firstName": "dd", "lastName": "dd" } but file content missing. One way of doing is using Directives. I want to know is this possible without Directive? @HemiplegiaMalia
@Malia my solution doesnt work with directives. So the answer is yes. What are you missing?Hemiplegia
Thanks for that but cant this possible in pure AngularJS instead of using JS part?@HemiplegiaMalia
@Malia Not possible, thats why I did not deliver you a answer which uses AngularJS core directives.Hemiplegia
How can I use the valid-file-upload only after click of submit button, currently what happening is while I upload the file it sends the data, I want that think on click of submit button alongwith form data this file data should go. @HemiplegiaMalia
@Malia i dont know. This is not my answer but you marked it as the right one. My answer is the other one.Hemiplegia

© 2022 - 2024 — McMap. All rights reserved.