Set max size for file input

前端 未结 2 2007
甜味超标
甜味超标 2021-01-17 01:40

I have used HTML file input to select a file for uploading using a custom AngularJS directive. Now I want to set the max allowed file size for the input. If the file size is

2条回答
  •  庸人自扰
    2021-01-17 02:36

    Took some liberty and changed your directive implementation a little bit as you are just binding the path of the file to your ng-model instead of file data.Also added the file size check (Max 2000 Bytes) which can changed as preferred. Here is the working plunker.

    Changed directive in JS

    angular.module('myApp', ['ng'])
    
        .directive('validFile', function($parse) {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function(scope, el, attrs, ngModel) {
                    var model = $parse(attrs.ngModel);
                    var modelSetter = model.assign;
                    var maxSize = 2000; //2000 B
                    el.bind('change', function() {
    
                        scope.$apply(function() {
                            scope.ebook.maxSizeError = false;
                            if (el[0].files.length > 1) {
                                modelSetter(scope, el[0].files);
                            } else {
                                modelSetter(scope, el[0].files[0]);
                            }
                            var fileSize = el[0].files[0].size;
                            if (fileSize > maxSize) {
                                scope.ebook.maxSizeError = true;
                            }
                        });
                    });
                }
            }
        })
        .controller('Ctrl', ['$scope', function($scope) {
            $scope.ebook = {};//scope object to hold file details
            $scope.uploadDocs = function() {
                var file = $scope.ebook.file;
                console.log(file);
            };
        }]);
    

    In your HTML

    
    
      
      
        E-Book is required.
      
      

    Max file size exceeded (2000 bytes)

提交回复
热议问题