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.
[TypeScript]
It's possible to check only the file extension, but user can easily rename virus.exe to virus.jpg and "pass" the validation.
For what it's worth, here is the code to check file extension and abort if does not meet one of the valid extensions: (choose invalid file and try to submit to see the alert in action)
Note, the code will allow user to send without choosing file... if it's required, remove the line
if (sFileName.length > 0) {
and it's associate closing bracket. The code will validate any file input in the form, regardless of its name.This can be done with jQuery in less lines, but I'm comfortable enough with "raw" JavaScript and the final result is the same.
In case you have more files, or want to trigger the check upon changing the file and not only in form submission, use such code instead:
This will show alert and reset the input in case of invalid file extension.