Search code examples
htmlimageinputfile-upload

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


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?


Solution

  • Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:

    <label>Your Image File
      <input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
    </label>

    Or simply:

    <label>Your Image File
      <input type="file" name="myImage" accept="image/*" />
    </label>

    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