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

- 480,997
- 81
- 517
- 436
-
18And bind it to your form: `$("#my_upload_form").bind("submit", function() { // above check });` – 321X Jun 23 '11 at 13:32
-
7you could use `$('#file_field').change(function(){// above check});` – makki Mar 10 '12 at 17:27
-
3`$("#my_upload_form").bind("submit", function() { // above check });` should now be bound using `$("#my_upload_form").submit(function() { // above check });` http://api.jquery.com/submit/. you can also prevent the form submitting using `$("#my_upload_form").submit(function(e) { // above check e.preventDefault(); });` – Liam Sep 24 '12 at 09:50
-
1In this case, if user would add `".jpg"` for example to MS Word file, FileUpload would accept this file as picture. I think it is not right. – Jeyhun Apr 08 '14 at 07:00
-
1@Jeyhun: The word "superficially" was bolded for a reason. This will not stop a malicious user from uploading a file you don't want by changing the file type, but it will work for 99% of cases. For more robust checking, you have to check server side. – Paolo Bergantino Apr 08 '14 at 17:00
-
3Its worth stating that this isn't a fool proof method.. At the end of the day make sure your backend is checking the first few bytes of the file to make sure it is infact the file type you really want it to be. Another thing to think about is, in linux and osx you can have a file without an extension thats actually of the type you want.. so this would fail on that also – chris Jul 09 '15 at 20:50
-
what happen some one upload file.png.php ? – Nov 01 '16 at 12:53
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.

- 441
- 4
- 2
-
6sorry bro, but that is a bad regex. files are allowed to have dots in its name. "giel.asd.aaaaa.jpg.png".match(/\.(.+)$/) – Tim Kretschmer Jul 27 '15 at 15:39
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:

- 1
- 1

- 1,249
- 2
- 15
- 23
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 ;)

- 1
- 1

- 11,346
- 1
- 29
- 29
-
can you provide example how to use this with http://plugins.krajee.com/file-input#option-allowedfileextensions on IE11 – shorif2000 Feb 22 '16 at 17:07
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 />

- 2,331
- 2
- 19
- 17
-
doesn't get what he need. it's just for easier handling to select an image from a folder with different extension. as you can see here -> http://imageshack.us/a/img20/8451/switchzz.jpg – bernte May 24 '13 at 18:38
-
As it doesn't hurt IE<10, and doesn't hurt other code, it's an effective restriction on what you're trying to restrict. – Leo Nov 29 '17 at 19:54
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');
}

- 1,125
- 1
- 12
- 19
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
}
}

- 1,651
- 3
- 27
- 37
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!');
}
}

- 865
- 1
- 9
- 14
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; }
});
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;
}
});

- 36,338
- 80
- 323
- 498
-
Could you please suggest how to restrict image size. For example, 10mb size image should not accept – PDSSandeep Jun 25 '18 at 16:00
-
@PDSSandeep Check this link pls https://stackoverflow.com/questions/6575159/get-image-dimensions-with-javascript-before-image-has-fully-loaded – NoWar Jun 26 '18 at 03:41
<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>

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

- 797
- 11
- 22
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;
}

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

- 81
- 1
- 3