Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating file extension in AngularJs before uploading

I am uploading images for our application to the server. Is there any way to validate the extensions in client side by JS before submitting them to the server before uploading them to server?

I am using AngularJs to handle my front-end.

like image 513
Ali Saberi Avatar asked Apr 21 '15 17:04

Ali Saberi


People also ask

How do I validate file extensions?

Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.

How does angular validate file size?

Check File Size before Uploading it in Angular Uploader component. By using uploading event, you can get the file size before upload it to server. File object contains the file size in bytes only. You can convert the size to standard formats ( KB or MB ) using bytesToSize method.

How do I restrict upload size in angular 8?

You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.


2 Answers

You can use this simple javascript to validate. This code should be put inside a directive and on change of file upload control.

var extn = filename.split(".").pop();

Alternatively you can use javascript substring method also:

fileName.substr(fileName.lastIndexOf('.')+1)
like image 177
Sanjeev Singh Avatar answered Sep 28 '22 10:09

Sanjeev Singh


You can create a angular directive, something like this should work (Change the accepted values in the validFormats array);

HTML:

    <form name='fileForm' >
        <input type="file" name="file" ng-model="fileForm.file" validfile>
    </form>

Javascript:

angular.module('appname').directive('validfile', function validFile() {

    var validFormats = ['jpg', 'gif'];
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            ctrl.$validators.validFile = function() {
                elem.on('change', function () {
                   var value = elem.val(),
                       ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();   

                   return validFormats.indexOf(ext) !== -1;
                });
           };
        }
    };
});
like image 42
ecarrizo Avatar answered Sep 28 '22 08:09

ecarrizo