How to Accept Only Image for File Input Type in HTML
Table of Contents
The web allows you to create inputs to accept things like text, email, password, and files simply by changing the type attribute.
When it comes to files, by default it will accept all file types.
However, you can restrict the types of files that can be uploaded to just images if you want.
In this post, we'll learn how to only allow images to be uploaded into a file input field in HTML.
How to only accept images in a file input field
As mentioned before, you can use an input type of file
to accept file uploads.
It looks like this:
HTML<input type="file" name="file-input">
This will accept all file extensions but if you add an accept
attribute, you can restrict the extensions that it will accept, like this:
HTML<input type="file" name="file-input" accept="image/*">
You can even be more specific and add MIME types to the accept
attribute, like so:
HTML<input type="file" name="file-input" accept="image/jpeg, image/png">
This attribute will only accept files that are of type image/jpeg
or image/png
.
If you only want to accept gif
files, you can use this:
HTML<input type="file" name="file-input" accept="image/gif">
Either way, you have full control over what files are accepted by specifying the file extensions in that attribute.
Conclusion
In this post, we learned how to specify the types of files that are allowed to be uploaded to a file input field.
To only allow for images, you can use the accept
attribute and pass it the file formats you want.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js