I need to upload only image file through <input type="file">
tag.
Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions which include .jpg
, .gif
etc.
How can I achieve this functionality?
Use the accept attribute of the input tag. So to accept only PNGs, JPEGs and GIFs you can use the following code:
<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
Or simply:
<input type="file" name="myImage" accept="image/*" />
Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.
It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.
For detailed browser support, see http://caniuse.com/#feat=input-file-accept