W3docs

How to Allow the File Input Type to Accept Only Image Files

In this tutorial, we’ll show how to allow the file input type to accept only image files or certain image file extensions. Use the HTML “accept” attribute.

Solution with HTML attributes

If you use <kbd class="highlighted"> XFI2 </kbd>, it will accept all file types. But it is possible to restrict the file types to only images, or certain image file extensions. To achieve this, you need to use the HTML accept attribute. This attribute is only used with <kbd class="highlighted"> XFI3 </kbd> and serves as a filter to select file inputs from the file input dialog box.

Let’s see an example.

Example of restricting the “file” input type to images:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <input type="file" id="img" name="img" accept="image/*" />
  </body>
</html>

Now, the type of the <input> element can accept only images.

If you want to specify the image file extensions, try the following example.

Example of restricting the “file” input type to image file extensions:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
  </body>
</html>
Warning

The <span class="attribute">accept</span> attribute should not be used as a validation tool. File uploads must be validated on the server.

Warning

The support is sketchy on mobiles.