如何在AngularJS中限制附件(文件上传)的大小?

时间:2014-02-24 10:47:41

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat angular-ui

我希望在AngularJS中使用加载图像上传文件的最佳方法。同时我想将大小限制为10MB。

请提供最佳方法来实现这一目标?

5 个答案:

答案 0 :(得分:10)

虽然这个问题有些陈旧,但我仍然认为为那些寻求它的人提供最好的答案是值得的。上面的答案依赖于jQuery的表面方面,但让我们使用适合Angular开发的样式。

在这里,当我被问到同一个问题时,我会引用actual library author's own recommendation,并根据上述问题中提到的大小改变它:

uploader = new FileUploader();
//...
uploader.filters.push({
    'name': 'enforceMaxFileSize',
    'fn': function (item) {
        return item.size <= 10485760; // 10 MiB to bytes
    }
});

上面的示例: 以反映对angular-file-upload API的更改。

请注意,这取决于文件的size属性(Blob size in bytes),该属性仅受现代浏览器支持(即IE10及更高版本)。

答案 1 :(得分:5)

您可以使用此lib:

https://github.com/danialfarid/ng-file-upload

  ngf-min-size='10' // minimum acceptable file size in bytes
  ngf-max-size='1000' // maximum acceptable file size in bytes

答案 2 :(得分:4)

看到这个例子,你会有一些想法

HTML CODE:

  <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>

SCRIPT:

$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more than ' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct - '+fileSize+' bytes');
            }
        }else{
            alert('Please select the file to upload');
            return false;
        }

    });
});

已经在jsfiddle

答案 3 :(得分:0)

这是我用来将文件拉入Angulars范围,验证文件大小和验证扩展的指令。

var fileUpload = () => {

    return {
        scope: {
            file: '='
        },
        require: 'ngModel',
        link(scope, el, attrs, ctrl) {

            el.bind('change', (event) => {
                var file = event.target.files[0];
                var extn = file.name.split(".").pop().toLowerCase();

                if (attrs.validExtensions != null) {
                    const extensions = attrs.validExtensions.split(',');
                    var validExtension = false;

                    extensions.forEach((x) => {
                        if (x === extn) {
                            validExtension = true;
                        }
                    });

                    ctrl.$setValidity('type', validExtension);
                }

                if (attrs.maxSize != null) {
                    var maxSize = attrs.maxSize;

                    var valid = (file.size / 1024) <= maxSize;
                    ctrl.$setValidity('size', valid);
                } else {
                    console.log('max size ScriptNotifyEvent set');
                }

                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
};

HTML

<input type="file" file="File1" id="File1" name="File1" ng-model="File1" valid-extensions="doc,docx,xls,xlsx,pdf,tiff,zip,ppt,pptx" max-size="20000" />

<div class="alert alert-danger" ng-show="form.File1.$error.type && (form.File1.$touched || Submitted)" Role="alert">This form only allows the following file types: *.doc, *.docx, *.xls, *.xlsx, *.ppt, *.pptx, *.pdf, *.tiff, *.zip</div>

<div class="alert alert-danger" ng-show="form.File1.$error.size && (form.File1.$touched || Submitted)" Role="alert">The file is too large to send to us, please limit indivudual files to 20 megabytes.</div>

答案 4 :(得分:0)

使用指令

ngApp.directive('fileModel', ['$parse', function ($parse) {

return {

restrict: 'A',

link: function (scope, element, attrs) {

var model = $parse(attrs.fileModel);

var modelSetter = model.assign;

 element.bind('change', function () {

var fileSize = this.files[0].size / 1024;

if (fileSize > 600) {

alert("File size is larze; maximum file size 600 KB");

} else {

scope.$apply(function () {

 modelSetter(scope, element[0].files[0]);

 });                
}          
 });    
 }   
};
}]);