使用angularjs验证文件大小以在上传前进行检查(input type=file)

9

我在表单中有一个文件类型的输入元素。我想创建一个自定义指令,在使用输入元素选择文件后立即检查文件大小。我知道如何创建自定义指令,但在AngularJS中是否有一种方法可以确定所选元素的文件大小。不要使用JQuery。

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

是的,这是可能的,但不特定于Angular - https://dev59.com/l3A65IYBdhLWcg3wogEb。您可以轻松地将其合并到Angular验证指令中。 - pixelbits
AI:你能整合并提供一下对你有效的解决方案吗?谢谢! - PavanSandeep
1个回答

9
如何从指令中检查文件大小:
app.directive('checkFileSize',function(){
    return{
        link: function(scope, elem, attr, ctrl) {
            $(elem).bind('change', function() {
              alert('File size:' + this.files[0].size);
          });
        }
    }
});

非 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


这个可以工作。但是似乎它使用了jQuery。你有没有不使用jQuery的解决方案? - A.I
基本上,在我们的链接函数中,elem[0].files[0].size 就可以完成任务。 - A.I
可以请您汇总并提供解决方案吗?谢谢! - PavanSandeep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接