Today, we will see how to upload file using angularjs.

Now let's start with step by step.

1] Script(folder) - app.js, directive.js

2] View(folder) - fileUpload.html

3] Controller(folder) - fileUploadController(.js file)

4] Service(folder) - fileUploadService(.js file)

Step 1. Create modular file (app.js).

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

Step 2. Create View file (fileUpload.html).

<div ng-app="app"> <div ng-controller="fileUploadController"> <form name="createTemplateForm" role="form"> <div class="form-group" ng-class="{' your class name' : createTemplateForm.fileUpload.$invalid && createTemplateForm.fileUpload.$dirty}"> <input type="file" name="fileUpload" class="form-control" upload-files required> <span ng-show="invalidFile " style="color:#a94442" class="animated fadeInDown help-block m-b-none">Upload text file</span> <button type="button" ng-disabled="createTemplateForm.$invalid" ng-click="submit()" class="btn btn-w-m buttonColorSet pull-right" style="margin: 0;">Create</button> </div> </form> </div> </div>

Step 3. Create Controller file (fileUploadController.js).

app.controller('fileUploadController', ['$scope', 'fileUploadService', function($scope,fileUploadService) { $scope.invalidFile = false; $scope.files = []; $scope.$on("seletedFile", function (event, args) { debugger; $scope.$apply(function () { if (args.file != undefined) { debugger; var allowedFiles = [".txt"]; var fileUpload = args.file; var regex = new RegExp("([a-zA-Z0-9s_\.-:])+(" + allowedFiles.join('|') + ")$"); if (!regex.test(fileUpload.name.toLowerCase())) { $scope.invalidFile = true; return false; } else { $scope.invalidFile = false; //add the file object to the scope's files collection $scope.files.push(args.file); } } else { $scope.invalidFile = false; } }); }); $scope.submit = function () { debugger; if ($scope.files != "" && $scope.invalidFile == false) { fileUploadService.upload($scope.files).then(function () { debugger; console.log("file upload Successfully"); }, function () { console.log("Error while uploading file"); }); $scope.invalidFile = false; } else { $scope.invalidFile = true; } } }]);

Step 4. Create Service(factory) file (fileUploadService.js).

app.factory('fileUploadService', ['$http', function ($http) { var serviceCallUrl = 'http://localhost:9999/'; var fileUploadServiceFactory = {}; var _upload = function (files) { return $http({ method: 'POST', url: serviceBase + "api/file/Upload", headers: { 'Content-Type': undefined }, data: { files: files }, transformRequest: function (data) { var formData = new FormData(); formData.append("model", angular.toJson(data.model)); for (var i = 0; i < data.files.length; i++) { formData.append("file" + i, data.files[i]); } return formData; }, }); } }; fileUploadService.getAllUsers = _upload; return fileUploadService; }]);

Step 5. Create directive file(directive.js).