How to make sure your input field can only upload images
I had the need to have a file upload for images, so I added my little input type="file"
field:
<input type="file">
I only wanted images to be allowed to be uploaded by the browser.
It’s a common thing, but I always forget how to do it.
Use the accept
attribute and pass image/*
to allow all images:
<input type="file" accept="image/*">
Or image/png
to only accept PNG images:
<input type="file" accept="image/png">
The same syntax can be done to only accept videos:
<input type="file" accept="video/*">
or audio:
<input type="file" accept="audio/*">
Or a combination of them:
<input type="file" accept="image/*,audio/*,video/*">
Oh common thing - add multiple
to allow uploading more than one:
<input type="file" multiple accept="image/*">
Of course this is only client-side validation, and you should also validate the mime type on the server when you receive the files.
→ Get my HTML Handbook
→ Read my HTML Tutorial
on The Valley of Code
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X