简体   繁体   English

使用angularjs在输入type = file之前验证文件大小

[英]validate file size before upload for input type=file using angularjs

I have an input type=file element in my form. 我的表单中有一个input type = file元素。 I want to create a custom directive for checking the file size as soon as I select a file using the input element. 我想使用input元素选择文件时创建一个自定义指令来检查文件大小。 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. 我知道如何创建一个创建自定义指令,但是在angularjs中有任何方法来确定所选元素的文件大小。 No Jquery is to be used. 不使用Jquery。

The js code: js代码:

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;
            });
        }
    }
});

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: 非jquery版本:

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 http://plnkr.co/edit/ybuk6K6YNTIwnLTK5I6Z?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM