user1429166
user1429166

Reputation: 131

How to access file in renderer function?

I saw a solution to: How to validate form with input[type=file] in angularjs

I was wondering if it is possible to check e.g. the mimetype or the file size inside the renderer? I dont only want to set the current selected file (for required input field file) i also like to check if the file is too large.

Upvotes: 0

Views: 52

Answers (1)

Tyler.z.yang
Tyler.z.yang

Reputation: 2450

Yes you can do that. With file api. In file change callback, you can handle the file with this code:

myApp.directive('validFile', function () {
    return {
        require: 'ngModel',
        link: function (scope, el, attrs, ngModel) {
            var maxSize = 100;
            var invalidSize = true;
            ngModel.$render = function () {
                // when you setValidity 'invalidSize' to false
                // then you 'form.myfile.$error.invalidSize' will be true.
                ngModel.$setValidity('invalidSize', invalidSize);
            };
            el.bind('change', function(evt){
                console.log(evt);
                var files = evt.target.files; // You can handle multifile here but need input file set multiple attribute
                var file = files[0];
                console.log(file); // You can see all these attribute here.
                console.log(file.size);
                if(file.size > maxSize){
                    invalidSize = false;
                }else{
                    invalidSize = true;
                }
                scope.$apply(ngModel.$render);
            });
        }
    };
});

Here is file api document.

Here is DEMO Code.

Upvotes: 1

Related Questions