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
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Deepak Mittal
Deepak is a bright web Developer. Deepak has expertise in Java.