AngularJS Upload File Application

In AngularJS we have the functionality of receiving and sending information to a remote HTTP.

Therefor we, will see how to make an upload file application using AngularJS and the $http service.

Therefor we, will see how to make an upload file application using AngularJS and the $http service.

The ng-model directive in AngularJS does not work with the file input element. A custom directive lets us "listen" to any change that occurs in the element. This can be achieved by the directives link option.

The attribute known as ng-files has been attached to input file element. A directive is created in the controller matching the attribute, so that the file input element can be accessed. The attribute has a function named getTheFiles() with a parameter $files. WE first initialize the parameter $files in the directive and later give a function call getTheFiles() using the controller's scope, along with $files parameter.

The Directive and Controller

There are two parts in the script. The first is the directive named as ngFiles and the second part is the controller.

The Custom Directive- "ngFiles"

To get the values ew use the $parse service in AngularJS. A $parse takes an expression and returns a function and our link option. Moreover, it needs a function to return. The parsed function onChange will have two parameters. The first parameter is the scope and the second will add the files details in $files variable through the event object.

The Controller

Using getTheFiles() function, the files in the controller can be accessed. The parameter $file provides details of the file. The change callback in the directive triggers this development.

After obtaining all the details, we run a loop using angular.forEach() to extract each file and save it in a FormData() object. To provide data to the $http service, the FormData object is used where data property is used.

						
<html>
   <head>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>
   <body ng-app = "myApp">
      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>
      <script>
         var myApp = angular.module('myApp', []);
         myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  var model = $parse(attrs.fileModel);
                  var modelSetter = model.assign;
                  
                  element.bind('change', function(){
                     scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                     });
                  });
               }
            };
         }]);
      
         myApp.service('fileUpload', ['$http', function ($http) {
            this.uploadFileToUrl = function(file, uploadUrl){
               var fd = new FormData();
               fd.append('file', file);
               $http.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })
            
               .success(function(){
               })
            
               .error(function(){
               });
            }
         }]);
      
         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
            $scope.uploadFile = function(){
               var file = $scope.myFile;
               
               console.log('file is ' );
               console.dir(file);
               
               var uploadUrl = "/fileUpload";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);
			
      </script>
      
   </body>
</html>