[javascript] How to have jQuery restrict file types on upload?

I would like to have jQuery limit a file upload field to only jpg/jpeg, png, and gif. I am doing backend checking with PHP already. I am running my submit button through a JavaScript function already so I really just need to know how to check for the file types before submit or alert.

This question is related to javascript jquery file-upload file-type

The answer is


function validateFileExtensions(){
        var validFileExtensions = ["jpg", "jpeg", "gif", "png"];
        var fileErrors = new Array();

        $( "input:file").each(function(){
            var file = $(this).value;
            var ext = file.split('.').pop();
            if( $.inArray( ext, validFileExtensions ) == -1) {
                fileErrors.push(file);
            }
        });

        if( fileErrors.length > 0 ){
            var errorContainer = $("#validation-errors");
            for(var i=0; i < fileErrors.length; i++){
                errorContainer.append('<label for="title" class="error">* File:'+ file +' do not have a valid format!</label>');
            }
            return false;
        }
        return true;
    }

Don't want to check rather on MIME than on whatever extention the user is lying? If so then it's less than one line:

<input type="file" id="userfile" accept="image/*|video/*" required />

    $("input[name='btnsubmit']").attr('disabled', true);
    $('input[name="filphoto"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) 
    {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'bmp':
        $("input[name='btnsubmit']").attr('disabled', false);
    break;
    default:
        alert('This is not an allowed file type.');
        $("input[name='btnsubmit']").attr('disabled', true);
        this.value = '';

for my case i used the following codes :

    if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {              
    alert('You must select an image file only');               
    }

You could use the validation plugin for jQuery: http://docs.jquery.com/Plugins/Validation

It happens to have an accept() rule that does exactly what you need: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension

Note that controlling file extension is not bullet proof since it is in no way related to the mimetype of the file. So you could have a .png that's a word document and a .doc that's a perfectly valid png image. So don't forget to make more controls server-side ;)


<form enctype="multipart/form-data">
   <input name="file" type="file" />
   <input type="submit" value="Upload" />
</form>
<script>
$('input[type=file]').change(function(){
    var file = this.files[0];
    name = file.name;
    size = file.size;
    type = file.type;
    //your validation
});
</script>

This code works fine, but the only issue is if the file format is other than specified options, it shows an alert message but it displays the file name while it should be neglecting it.

$('#ff2').change(
                function () {
                    var fileExtension = ['jpeg', 'jpg', 'pdf'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
                        return false; }
});

No plugin necessary for just this task. Cobbled this together from a couple other scripts:

$('INPUT[type="file"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
            $('#uploadButton').attr('disabled', false);
            break;
        default:
            alert('This is not an allowed file type.');
            this.value = '';
    }
});

The trick here is to set the upload button to disabled unless and until a valid file type is selected.


For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.

Example:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:


If you're dealing with multiple (html 5) file uploads, I took the top suggested comment and modified it a little:

    var files = $('#file1')[0].files;
    var len = $('#file1').get(0).files.length;

    for (var i = 0; i < len; i++) {

        f = files[i];

        var ext = f.name.split('.').pop().toLowerCase();
        if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
            alert('invalid extension!');

        }
    }

This example allows to upload PNG image only.

HTML

<input type="file" class="form-control" id="FileUpload1" accept="image/png" />

JS

$('#FileUpload1').change(
                function () {
                    var fileExtension = ['png'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.png' format is allowed.");
                        this.value = ''; // Clean field
                        return false;
                    }
                });

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("");
    }
}

I try to write working code example, I test it and everything works.

Hare is code:

HTML:

<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />

Javascript:

 //function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
    var val = $(element).val(); //get file value

    var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention 
    if ($.inArray(ext, extentionsArray) == -1) {
        alert('false extension!');
    }

    var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
    if (fileSize > maxSize) {
        alert("Large file");// if Maxsize from Model > real file size alert this
    }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to file-type

Upload DOC or PDF using PHP Node.js get file extension Full path from file input using jQuery What do .c and .h file extensions mean to C? How to have jQuery restrict file types on upload?