You can not read the file if your browser doesn't supports FileReader API.
Your directive is applied on a file upload control. So, you can listen to its change event. With this change event, you can extract the file object provided in event, emit an event to catch it the controller.
app.directive('fileUpload', function () {
return {
scope: true,
link: function (scope, element, attrs) {
/*Every time you select a file or a multiple files, change event is triggered.
So, with this on, we are attaching a listener event to it. This event also contains useful data. Like the array of selected files.
So, we iterate over the selected files, and emit an event containing file info.*/
element.on('change', function (event) {
var files = event.target.files;
for (var i = 0;i<files.length;i++) {
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};
With this code, you are listening to a file upload control's change event. On change, you are emitting an event called fileSelected
, that you will receive in controller.
function DefaultController($scope){
$scope.files = [];
$scope.$on('fileSelected', function($event, args){
$scope.files.push( args.file );
};
Please note that, with this code, you are only adding file objects in your scope. You still need to send a request to upload file.
You can use fallowing code taken from with a little bit of correction.
$http({
method: 'POST',
url: "/Api/PostStuff",
headers: { 'Content-Type': undefined},
transformRequest: function (data) {
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
for (var i = 0; i < data.files.length; i++) {
formData.append("file" + i, data.files[i]);
}
return formData;
},
data: { model: $scope.model, files: $scope.files }
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});