Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
            });
        }
    }
});
like image 263
A.I Avatar asked Sep 17 '14 08:09

A.I


People also ask

How to check uploaded file size in angular?

Check File Size before Uploading it in Angular Uploader component. By using uploading event, you can get the file size before upload it to server. File object contains the file size in bytes only. You can convert the size to standard formats ( KB or MB ) using bytesToSize method.

How to restrict the file size while uploading in angular?

You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.


1 Answers

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

like image 103
Marian Ban Avatar answered Oct 24 '22 01:10

Marian Ban