How to Restrict File Uploads to Only Accept Images
When you add a file field to a form, it can be useful to limit the selection to only images. This not only enhances user experience by avoiding wasted time and resources in uploading non-image files, but also adds a client-side filtering capability to complement your server-side filtering.
To achieve this, you can utilize the accept
attribute of the <input type="file">
element, specifying the MIME type of the accepted files. By setting the value to image/*
, you can allow all types of images.
Here’s an example:
1 | <input type="file" name="myImage" accept="image/*" /> |
Alternatively, if you only want to permit specific image file types, you can list them individually:
1 | <input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" /> |
To verify the browser support for this attribute, you can visit this link.
tags: [“client-side filtering”, “file upload”, “form validation”, “MIME type”]