Skip to content

How to make sure your input field can only upload images

New Course Coming Soon:

Get Really Good at Git

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my HTML Handbook
→ Read my HTML Tutorial on The Valley of Code

Here is how can I help you: