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?
Using type="file" and accept="image/*" (or the format you want), allow the user to chose a file with specific format. But you have to re check it again in client side, because the user can select other type of files.
By using multiple attribute you can upload multiple images in an instance. You can also limit multiple mime types. and another way of checking mime type using file object. file object gives you name,size and type.
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<input type="file" name="myImage" accept="image/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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With