I am trying to bind form-data along with image(s) from HTML page to Angular Controller, then append form-data with image data, and finally POST data to an API.
So I searched, and got to know that, sadly AngularJs doesn't have any directive for image files.
So the ultimate solution I got is to create a custom directive, append form-data with image(s), and then POST that data to server.
What I tried:
HTML
<form role="form" enctype="multipart/form-data" name="myForm">
<input type="text" ng-model="UserName" required="required">
<input type="text" ng-model="FirstName" required="required">
<input type="file" ng-model="Image" required="required">
<button type="submit" ng-click="product()">save</button>
</form>
Custom Directive :
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
POST Method :
scope.product = function() {
var pro = $scope.pro;
console.log('Form Data : ' + pro);
var fd = new FormData();
angular.forEach($scope.Image, function(file) {
fd.append('file', file);
});
fd.append('pro', JSON.stringify($scope.product));
$http.post('/products/createProduct', fd, {
transformRequest: angular.identity,
headers: {
'Content-type': undefined
}
})
.then(function(data) {
$scope.ListProducts = data;
console.log($scope.ListProducts );
});
}
But the problem is, nothing is binding to the controller, and every-time my object is empty.
I even tried logging data to console, but got nothing inside data.
I don't know what I am doing wrong.
Please help..
Update
I am able to bind data, but while posting image-path along with other form-data I am getting all null.
angular.js:14642 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/products/createProduct","data":{"productStock":[{"price":"","color":""}],"productThumbnail":{"0":{}}},"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":""} error