How to only accept images in an input file field
By Flavio Copes
Learn how to limit a file input to images using the accept attribute, setting image/* or specific MIME types like image/png to filter what users can upload.
Of course you could add a server-side filter, but also having a client-side filter is a great UX for your users - no time wasted and no resources wasted to send a file to you and get back with an error.
You can do so by using the accept attribute, and specifying the MIME type of the files you accept.
accept only filters what the file picker shows. It’s a hint, not a security check, so keep validating the file type on the server.
image/* should catch all images:
<input type="file" name="myImage" accept="image/*" />
If you want to only allow some specific file types, list them:
<input type="file" name="myImage" accept="image/png,image/gif,image/jpeg" />
You can also list file extensions instead of MIME types, and the picker filters on those:
<input type="file" name="myImage" accept=".png,.jpg,.jpeg,.gif" />
Add multiple if the user can pick more than one image:
<input type="file" name="gallery" accept="image/*" multiple />
On phones, the capture attribute asks the browser to open the camera instead of the photo library. Use user for the front camera and environment for the rear one:
<input type="file" name="photo" accept="image/*" capture="environment" />
Safari on iOS and Chrome on Android support capture. Desktop browsers ignore it and show the normal file picker.
Want me to talk about your product? You can sponsor this site.
Related posts about platform: