w3docs logo
  1. Snippets
  2. HTML
  3. How to Allow the File Input Type to Accept Only Image Files

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

Solution with HTML attributes

If you use <input type="file">, 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 <input type="file"> 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>
The accept attribute should not be used as a validation tool. File uploads must be validated on the server.
The support is sketchy on mobiles.
Do you find this helpful?