How to have jQuery restrict file types on upload?

JavascriptJqueryFile UploadFile Type

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

You can get the value of a file field just the same as any other field. You can't alter it, however.

So to superficially check if a file has the right extension, you could do something like this:

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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 ;)

Solution 4 - Javascript

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:

Solution 5 - Javascript

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 />

Solution 6 - Javascript

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');	           
    }

Solution 7 - Javascript

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
    }
}

Solution 8 - Javascript

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!');
           
        }
    }

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

<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>

Solution 12 - Javascript

    $("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 = '';

Solution 13 - Javascript

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;
    }

Solution 14 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthonyView Question on Stackoverflow
Solution 1 - JavascriptPaolo BergantinoView Answer on Stackoverflow
Solution 2 - JavascriptChristianView Answer on Stackoverflow
Solution 3 - JavascriptJulian AubourgView Answer on Stackoverflow
Solution 4 - JavascriptdhruvpatelView Answer on Stackoverflow
Solution 5 - JavascriptLeoView Answer on Stackoverflow
Solution 6 - JavascriptvanessenView Answer on Stackoverflow
Solution 7 - JavascriptAvtandil KavrelishviliView Answer on Stackoverflow
Solution 8 - JavascriptJason RonerView Answer on Stackoverflow
Solution 9 - JavascriptAbhiView Answer on Stackoverflow
Solution 10 - JavascriptNoWarView Answer on Stackoverflow
Solution 11 - JavascriptKhaihkdView Answer on Stackoverflow
Solution 12 - JavascriptThe EasyLearn AcademyView Answer on Stackoverflow
Solution 13 - JavascriptMuhammad Saqib SarwarView Answer on Stackoverflow
Solution 14 - JavascriptmatheushfView Answer on Stackoverflow