Posted by : at

Category : angularjs

AngularJS Upload Multiple Images

There are two methods :

  1. Using Custom Upload Directive
  2. Using ng-file-upload Directive -Github Repo Link

Method 1 - Using Custom Directive

create a index.html file. This will contain our form

index.html

<html ng-app="formApp">

<body>
<form ng-controller="formCtrl" enctype="multipart/form-data">

<label for="first-photo"> Upload Photo 1 </label>       
<input type="file" demo-file-model="formData.firstPhoto" id="first-photo">

<label for="second-photo"> Upload Photo 2 </label>       
<input type="file" demo-file-model="formData.secondPhoto" id="second-photo">


<label for="third-photo"> Upload Photo 3 </label>       
<input type="file" demo-file-model="formData.thirdPhoto" id="third-photo">	

<button type="submit" ng-click="submit()" id="formSubmitBtn"> Submit </button>
		
</form>

</body>
</html>

Create a app.js. This will contain our angular logic to bind our form elements

app.js

const app = angular.module("formApp");


// Image Upload Directive
app.directive("demoFileModel", function($parse) {
  return {
    restrict: "A", 
    link: function(scope, element, attrs) {
      var model = $parse(attrs.demoFileModel),
        modelSetter = model.assign; //define a setter for demoFileModel

      //Bind change event on the element
      element.bind("change", function() {
        //Call apply on scope, it checks for value changes and reflect them on UI
        scope.$apply(function() {
          //set the model value
          modelSetter(scope, element[0].files[0]);
        });
      });
    }
  };
});


// Image Upload Service
app.service("fileUploadService", [
  "$http",
  "$q",
  function($http, $q) {
    return {
      uploadFileToUrl: function(file, uploadFileUrl) {
        let formData = new FormData();
        formData.append("file", file);
        var deffered = $q.defer();
        $http({
          method: "POST",
          url: uploadFileUrl,
          headers: {
            "Content-Type": undefined
          },
          transformRequest: angular.identity,
          data: formData
        }).then(
          function(response) {
            let result = {
              success: true,
              message: "Image Uploaded Successfully",
              data: response
            };
            deffered.resolve(result);
          },
          function(response) {
            let result = {
              success: false,
              message: "Image Upload Failed",
              data: response
            };
            deffered.reject(result);
          }
        );
        return deffered.promise;
      }
    };
  }
]);

// Image Upload Controller
app.controller("formCtrl", ["$scope", "$rootScope", "$http", "$timeout", "fileUploadService",
function($scope, $rootScope, $http, $timeout, fileUploadService){
        
let first_photo = $scope.formData.firstPhoto;

let second_photo = $scope.formData.secondPhoto;

 let third_photo = $scope.formData.thirdPhoto;


        let values = [];

        // upload photo
        let uploadPhoto1 = fileUploadService.uploadFileToUrl(first_photo, '/api/upload-photo1');       
         let firstPromise = uploadPhoto1.then(function(response){
                   let photo1 = response.data.data.data.path;
                   return photo1;
                  },  function(error){
                        return error
                    });

        let uploadPhoto2 =   fileUploadService.uploadFileToUrl(second_photo,'/api/upload-photo2');            
        let secondPromise =   uploadPhoto2.then(function(response){
                let photo2 = response.data.data.data.path;
                return photo2;
            }, function(error){
              return error
            });

        let uploadPhoto3 = fileUploadService.uploadFileToUrl(third_photo, '/api/upload-photo3');
        let thirdPromise = uploadPhoto3.then(function(response){
            let photo3 = response.data.data.data.path;
            return photo3;
        }, function(error){
           return error
        });

$scope.submit = function() {

        let newValues = $q.all([firstPromise, secondPromise, thirdPromise]).then(function(result){
            for (let i = 0; i < result.length; i++){
                values.push(result[i]);
            }
            return values;
        })

	  newValues.then(function(response){

         $http({
              method: 'POST',
              url: '/api/submit-form',
              headers: {
                  'Content-Type': 'application/json'
               },
               data: {
                   first_photo_path: response[0],
                   second_photo_path: response[1],
        	   third_photo_path: response[2],
              }
      	   }).then(function (response){
              // data should be saved in to the mongodb
                 $scope.data = response.data;
           }, function (response){
                  $scope.data = response.statusText
           });
       },function(error){
           console.log(error);
       });
     }
	
}

});

Related Posts