I am using file reader to fetch the data of file upload. I am able to get the data in controller.js, but not able to pass it to the API service. The data is always passed as empty. I have updated the code as below:
//index.cshtml
<input type="file" my-files="files" />
<input type="button" name="imageUploadButton" ng-click="uploadFiles()" value="Upload" />
// controller.js
angular.module('myApp.controllers', []).
controller('AppController', function($scope, testAPIService, Excel, $timeout, $window, $location, $anchorScroll,$http) {
var url = "server/UploadImage/";
var config = {
headers: {
"Content-Type": undefined,
}
};
$scope.uploadFiles = function () {
var file = $scope.files[0];
$http.post(url, file, config).then(function (response) {
$scope.result = "SUCCESS";
$scope.data = response.data.data;
}).catch(function (response) {
alert( "ERROR " + response.status);
});
};
});
angular.module("myApp.controllers").directive("myFiles", function ($parse) {
return function linkFn(scope, elem, attrs) {
elem.on("change", function (e) {
scope.$eval(attrs.myFiles + "=$files", { $files: e.target.files });
scope.$apply();
console.log(scope);
});
};
});
angular.module("myApp.controllers").directive("xdHref", function () {
return function linkFn(scope, elem, attrs) {
scope.$watch(attrs.xdHref, function (newVal) {
newVal && elem.attr("href", newVal);
});
};
});
When the file is selected, "myFiles" directive is invoked, and i can see the data in console. When i click on the upload button, the below line is coming as error
var file = $scope.files[0];
How to fix this? Thanks
Uploading Files with AngularJS
HTML
my-files
DirectiveThe DEMO on PLNKR.