Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow <input type="file"> to accept only image files?

Tags:

html

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?

like image 407
kbvishnu Avatar asked Sep 30 '10 07:09

kbvishnu


People also ask

How do you make an input file only accept pictures?

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.

How do I restrict image type in HTML?

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.


1 Answers

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

like image 158
madcap laughs Avatar answered Sep 17 '22 07:09

madcap laughs