21

Is it possible to read files in AngularJS? I want to place the file into an HTML5 canvas to crop.

I was thinking of using a directive? This is the javascript code I want to put into my directive:

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

3 Answers 3

28

Yes, directives is a right way, but it looks little bit different:

.directive("ngFileSelect",function(){    
  return {
    link: function($scope,el){          
      el.bind("change", function(e){          
        $scope.file = (e.srcElement || e.target).files[0];
        $scope.getFile();
      });          
    }        
  }
})

Working example: http://plnkr.co/edit/y5n16v?p=preview

Thanks to lalalalalmbda for this link.

1
  • Is it possible to read a file without the "change" event? For example when Edit button is clicked to open a bootstrap modal and the value is set to the input file coming from the previous loaded data?
    – madsongr
    Jul 5, 2018 at 14:57
12

I've taken Cherniv's code and folded all of it into a directive:

.directive('fileSelect', ['$window', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, el, attr, ctrl) {
            var fileReader = new $window.FileReader();

            fileReader.onload = function () {
                ctrl.$setViewValue(fileReader.result);

                if ('fileLoaded' in attr) {
                    scope.$eval(attr['fileLoaded']);
                }
            };

            fileReader.onprogress = function (event) {
                if ('fileProgress' in attr) {
                    scope.$eval(attr['fileProgress'], 
                    {'$total': event.total, '$loaded': event.loaded});
                }
            };

            fileReader.onerror = function () {
                if ('fileError' in attr) {
                    scope.$eval(attr['fileError'], 
                    {'$error': fileReader.error});
                }
            };

            var fileType = attr['fileSelect'];

            el.bind('change', function (e) {
                var fileName = e.target.files[0];

                if (fileType === '' || fileType === 'text') {
                    fileReader.readAsText(fileName);
                } else if (fileType === 'data') {
                    fileReader.readAsDataURL(fileName);
                }
            });
        }
    };
}]);

You can then use the directive as follows:

<input type="file" ng-model="file.data" 
       file-select="data" 
       file-loaded="myLoaded()"
       file-error="myError($error)" 
       file-progress="myProgress($total,$loaded)">

Where "file.data", "myLoaded", "myError", and "myProgress" are in the enclosing scope.

0

Angular File reader.

link: function(scope, element, attrs) {
            element.on('change', function(e) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    scope.$apply(function() {
                       scope.onReadFile({$content:e.target.result});
                    });
                };
                reader.readAsText((e.srcElement || e.target).files[0]);
            });
        }

Live example : Live Run On Plunker

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.