I am uploading images to a servlet. The validation whether the uploaded file is an image is done in server side only, by checking the magic numbers in the file header. Is there any way to validate the extensions in client side before submitting the form to servlet? As soon as I hit enter it starts uploading.
I am using Javascript and jQuery in client side.
Update: I was finally ended up with server side validation which reads bytes & rejects the upload if it is not an image.
You can create an array that includes the filetype that is needed and use $.inArray() in jQuery to check if filetype exist in array.
check that if file is selected or not
check the file extension
None of the existing answers seemed quite compact enough for the simplicity of the request. Checking if a given file input field has an extension from a set can be accomplished as follows:
So example usage might be (where
upload
is theid
of a file input):Or as a jQuery plugin:
Example usage:
The
.replace(/\./g, '\\.')
is there to escape the dot for the regexp so that basic extensions can be passed in without the dots matching any character.There's no error checking on these to keep them short, presumably if you use them you'll make sure the input exists first and the extensions array is valid!
I like this example:
This is the best solution in my opinion, which is by far much shorter than the other ones:
In this case, the function is called from a Kendo Upload control with this setting:
.Events(e => e.Select("OnSelect"))
.Here is a more reusable way, assuming you use jQuery
Library function (does not require jQuery):
Page function (requires jQuery (barely)):