I am experiencing an issue with uploading a file to the server. The variable files in the for loop is showing up as undefined during debugging. Please review the directive to ensure it is correct.
HTML
<input type="file" accept=".xlsx" file-model/>
<button ng-click="upload()">upload me</button>
fileModel directive
app.directive('fileModel', function () {
return {
restrict: 'A',
transclude: true,
link: function($scope, $element) {
var fileInput = $element.find('input[type="file"]');
fileInput.bind('change', function(e) {
$scope.notReady = e.target.files.length == 0;
$scope.files = [];
for (var i in e.target.files) {
if (typeof e.target.files[i] == 'object')
$scope.files.push(e.target.files[i]);
}
});
}
};
});
Controller
$scope.upload = function() {
var uploadUrl = 'someurl';
UtilityService.upload($scope.files, $scope.user, uploadUrl);
};
Service
function UtilityService($http, $rootScope) {
var service = {};
service.upload=upload;
function upload(files, user, uploadUrl) {
var formData = new FormData();
for (var i in files) {
formData.append('file_' + i, files[i]);
}
formData.append("UserId", user.id);
formData.append("UserRole", user.roles);
$http({
method: 'POST',
url: config.server +uploadUrl,
enctype: "multipart/form-data",
data: formData,
headers: {
'Content-Type': undefined,
},
transformRequest: angular.identity
})
.success(function(data, status, headers, config) {
service.data = data;
});
}
return service;
}