Javascript 使用angularjs为输入类型=文件上传前验证文件大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25885341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:00:34  来源:igfitidea点击:

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

javascriptangularjsangularjs-directivefile-type

提问by A.I

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.

我的表单中有一个 input type=file 元素。我想创建一个自定义指令,用于在使用 input 元素选择文件后立即检查文件大小。我知道如何创建一个自定义指令,但是 angularjs 有什么方法可以确定所选元素的文件大小。不得使用 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;
            });
        }
    }
});

回答by Marian Ban

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