javascript - 使用angularjs在上传输入类型=文件之前验证文件大小

标签 javascript angularjs angularjs-directive file-type

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

最佳答案

如何通过指令检查文件大小:

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

关于javascript - 使用angularjs在上传输入类型=文件之前验证文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25885341/

相关文章:

javascript - Angular Directive(指令)范围值

javascript - 指令中的 ng-click 不起作用

javascript - 离线时获取 "real"设备时间的策略

javascript - CORS 适用于 chrome 但不适用于 firefox、angularjs

javascript - 当我使用 AngularJS $routeProvider 时,Node.js 页面转换不再起作用

javascript - 在指令中使用 $location.url() 在 angularjs 中不起作用

javascript - 用户可以在 AngularUI Datepicker 中输入无效日期

javascript - 内联 JavaScript 函数

javascript - JavaScript 中具有 parseInt 值 = NaN 的数字

javascript - 正则表达式从短代码标签解析键值对