[jquery] jquery - Check for file extension before uploading

I am using uploadify for uploading files with Codeigniter. And before uploading the file I just have to check whether the file extension is correct is correct or not. I have tried with http://jquery.bassistance.de/ and also http://forum.jquery.com/

Bur didn't got proper result. Can anyone please tell me how can I do the same?

Thanks in advance...

This question is related to jquery

The answer is


        function yourfunctionName() {
            var yourFileName = $("#yourinputfieldis").val();

            var yourFileExtension = yourFileName .replace(/^.*\./, '');
            switch (yourFileExtension ) {
                case 'pdf':
                case 'jpg':
                case 'doc':
                    $("#formId").submit();// your condition what you want to do
                    break;
                default:
                    alert('your File extension is wrong.');
                    this.value = '';
            }    
        }

Here is a simple code for javascript validation, and after it validates it will clean the input file.

<input type="file" id="image" accept="image/*" onChange="validate(this.value)"/>

function validate(file) {
    var ext = file.split(".");
    ext = ext[ext.length-1].toLowerCase();      
    var arrayExtensions = ["jpg" , "jpeg", "png", "bmp", "gif"];

    if (arrayExtensions.lastIndexOf(ext) == -1) {
        alert("Wrong extension type.");
        $("#image").val("");
    }
}

You can achieve this using JQuery

HTML

 <input type="file" id="FilUploader" />

JQuery

    $("#FilUploader").change(function () {
        var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
        if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
            alert("Only formats are allowed : "+fileExtension.join(', '));
        }
    });

For more info Click Here


If you don't want to use $(this).val(), you can try:

var file_onchange = function () {
  var input = this; // avoid using 'this' directly

  if (input.files && input.files[0]) {
    var type = input.files[0].type; // image/jpg, image/png, image/jpeg...

    // allow jpg, png, jpeg, bmp, gif, ico
    var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/;

    if (type_reg.test(type)) {
      // file is ready to upload
    } else {
      alert('This file type is unsupported.');
    }
  }
};

$('#file').on('change', file_onchange);

Hope this helps!


If you want to do it without a plugin you could use the following.

Javascript, using jQuery:

$(document).ready( function (){
    $("#your_form").submit( function(submitEvent) {

        // get the file name, possibly with path (depends on browser)
        var filename = $("#file_input").val();

        // Use a regular expression to trim everything before final dot
        var extension = filename.replace(/^.*\./, '');

        // Iff there is no dot anywhere in filename, we would have extension == filename,
        // so we account for this possibility now
        if (extension == filename) {
            extension = '';
        } else {
            // if there is an extension, we convert to lower case
            // (N.B. this conversion will not effect the value of the extension
            // on the file upload.)
            extension = extension.toLowerCase();
        }

        switch (extension) {
            case 'jpg':
            case 'jpeg':
            case 'png':
                alert("it's got an extension which suggests it's a PNG or JPG image (but N.B. that's only its name, so let's be sure that we, say, check the mime-type server-side!)");

            // uncomment the next line to allow the form to submitted in this case:
//          break;

            default:
                // Cancel the form submission
                submitEvent.preventDefault();
        }

  });
});

HTML:

<form id="your_form" method="post" enctype="multipart/form-data">
    <input id="file_input" type="file" />
    <input type="submit">
</form>

<!DOCTYPE html>
    <html>
      <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script>
         jQuery(document).ready(function(){
               jQuery('.form-file input').each(function () {
                     $this = jQuery(this);
                          $this.on('change', function() {
                               var fsize = $this[0].files[0].size,
                                   ftype = $this[0].files[0].type,
                                   fname = $this[0].files[0].name,
                                   fextension = fname.substring(fname.lastIndexOf('.')+1);
                                   validExtensions = ["jpg","pdf","jpeg","gif","png","doc","docx","xls","xlsx","ppt","pptx","txt","zip","rar","gzip"];

                                if ($.inArray(fextension, validExtensions) == -1){
                                    alert("This type of files are not allowed!");
                                    this.value = "";
                                    return false;
                                }else{
                                    if(fsize > 3145728){/*1048576-1MB(You can change the size as you want)*/
                                        alert("File size too large! Please upload less than 3MB");
                                        this.value = "";
                                        return false;
                                    }
                                    return true;
                               }

                         });
             });
       });
    </script>
    </head>

<body>
    <form>
          <div class="form-file">
               <label for="file-upload" class="from-label">File Upload</label>
               <input class="form-control" name="file-upload" id="file-upload" type="file">
          </div>
    </form>
</body>

</html>

Here is complete answer for checking file size and file extension. This used default file input field and jQuery library. Working example : https://jsfiddle.net/9pfjq6zr/2/


The following code allows to upload gif, png, jpg, jpeg and bmp files.

var extension = $('#your_file_id').val().split('.').pop().toLowerCase();

if($.inArray(extension, ['gif','png','jpg','jpeg','bmp']) == -1) {
    alert('Sorry, invalid extension.');
    return false;
}

 $("#file-upload").change(function () {

    var validExtensions = ["jpg","pdf","jpeg","gif","png"]
    var file = $(this).val().split('.').pop();
    if (validExtensions.indexOf(file) == -1) {
        alert("Only formats are allowed : "+validExtensions.join(', '));
    }

});