validate file size before upload for input type=file using angularjs

28,054

How to check file size from a directive:

app.directive('checkFileSize',function(){
    return{
        link: function(scope, elem, attr, ctrl) {
            $(elem).bind('change', function() {
              alert('File size:' + this.files[0].size);
          });
        }
    }
});

non jquery version:

app.directive('checkFileSize', function() {
  return {
    link: function(scope, elem, attr, ctrl) {
      function bindEvent(element, type, handler) {
        if (element.addEventListener) {
          element.addEventListener(type, handler, false);
        } else {
          element.attachEvent('on' + type, handler);
        }
      }

      bindEvent(elem[0], 'change', function() {
        alert('File size:' + this.files[0].size);
      });
    }
  }
});

http://plnkr.co/edit/ybuk6K6YNTIwnLTK5I6Z?p=preview

Share:
28,054
A.I
Author by

A.I

Updated on September 17, 2020

Comments

  • A.I
    A.I almost 4 years

    I have an input type=file element in my form. I want to create a custom directive for checking the file size as soon as I select a file using the input element. I know how to create a create a custom directive, but is there any way in angularjs to determine the file size of the selected element. No Jquery is to be used.

    The js code:

    app.directive('checkFileSize',function(){
        return{
            require: 'ngModel',
            link: function(scope, elem, attr, ctrl) {
                // add a parser that will process each time the value is
                // parsed into the model when the user updates it.
                ctrl.$parsers.unshift(function (value) {
                    //i want to do something like this  
                    var fileSize= // get file size here
                    if(fileSize>threshold){
                        ctrl.$setValidity('checkFileSize',false);    
                    }
                    // return the value to the model,
    
                    return someValue;
                });
            }
        }
    });