Multipart file uploading in AngularJS

Posted By : Deepak Mittal | 12-Nov-2014

What happens when you’re working with AngularJS and need to perform a multipart/form-data file upload? I’ve seen several solutions to this problem, and many seem a bit intimidating for a beginner. While tackling this problem myself, I put together a simple Work in my Controller.

 

  var myApp = angular.module('myApp', []); myApp.controller('myCtrl', ['$scope', function($scope){ $scope.selectedFile=[]; $scope.onFileSelect = function ($files) { $scope.uploadProgress = 0; $scope.selectedFile = $files; }; $scope.myData = {}; $scope.upload = function(){ var formData = new FormData(); if($scope.selectedFile[0]) { formData.append("file", $scope.selectedFile[0]); } formData.append("defaulter",defaulter); formData.append("data", myData.message.value); $http.post('api/upload', formData, { transformRequest: angular.identity, headers: { 'enctype': 'multipart/form-data', 'Content-Type': undefined } }) .success(function(){ alert("succesful uploaded ") }) .error(function(){ alert("unsuccesful uploading") }); }; }]);
 
<form><b>Message</b><br />
<textarea name="message" ng-minlength="15" ng-model="message" placeholder="Send Message" required="" rows="3"></textarea> <input accept="image/*" name="file" ng-file-select="onFileSelect($files)" type="file" /><button class="btn btn-primary" ng-click="upload()" type="submit">submit</button></form>
 
   

Thanks

 

Deepak Mittal

 

About Author

Author Image
Deepak Mittal

Deepak is a bright web Developer. Deepak has expertise in Java.

Request for Proposal

Name is required

Comment is required

Sending message..