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
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook