How to upload file in angularjs? - CodingPot | Programming Blog - C#, VB.Net, ASP.Net, MVC, Angularjs Tutorials

Friday, 3 February 2017

How to upload file in angularjs?

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).


function uploadFiles() { return { scope: true, //create a new scope link: function (scope, el, attrs) { el.bind('change', function (event) { debugger; var files = event.target.files; //iterate files since 'multiple' may be specified on the element for (var i = 0; i < files.length; i++) { debugger; //emit event upward scope.$emit("seletedFile", { file: files[i] }); } //scope.$emit("seletedFile", { file: files[i] }); }); } }; } app.directive("uploadFiles", uploadFiles);

2 comments:

  1. How can i implement this code to upload multiple files at once, i am creating a storage system for users there they can select multiple files at once, suppose i want to upload pdf, mp3, doc, video, .exe files then what will be the files uploading code since i am creating multiple upload system.
    one more thing i want to ask you that how will i make it happen for drag and drop upload with html5 api is there any additional code that i need to update with your given script.

    Hope i am not bothering you, one more thing want to ask please don't get fussed, what about security for uploading files since security is major point for applications to prevent malicious attacks ?

    hoping to hearing back from you soon :)

    thanks

    Regards

    Rajul Mishra.

    ReplyDelete
  2. Hi Rajul Mishra,

    You can implement code to upload multiple files at once.
    You can drag and drop your files.

    I suggest to you for this implement that is (Dropzone) http://www.dropzonejs.com/.

    Find out more from this site.

    I am waiting, if you have any query.

    ReplyDelete