How to make `` accept only specific file types?
Define the acceptable file types for your <input type="file"/>
by setting the accept
attribute.
This configuration narrow downs the file dialog, displaying only .jpg and .png files.
In-depth understanding of the accept
attribute
The accept
attribute in an HTML <input>
tag acts as a filter for the file input dialog box in browsers. This filter advises the browser on which file types should be displayed for selection to the user. While it's not a rock-solid means of validation, it provides a guiding mechanism for users in selecting appropriate file types.
File extension and MIME types
You can use either specific file extensions or MIME types (a category of file types) in the accept
attribute. File extensions should be prefixed with a period (".gif"), and MIME types should follow the type/*
format ("audio/*").
MIME types preferred
For greater compatibility across browsers, using MIME types is advised over file extensions. Each MIME type includes a type
and a subtype
, joined by a slash, like application/pdf
. It's more reliable than its file extension counterpart (".pdf").
Accept multiple file types
The accept
attribute also accepts a comma-separated list of both file extensions and MIME types.
Consider the order of types
The sequence of types may impact the default selection in the file dialog box. For instance, putting "image/*" at the end may make the browser prioritize specific file types.
Ensure MIME types for each Office formats
Considering different versions of software like MS Office is a good practice. Including both new and old formats ensures a smooth upload experience for all users.
Test behaviors in different browsers
Browsers behave differently. A point in case is Firefox, which may not fully recognize file extensions as opposed to MIME types, necessitating cross-browser testing.
The ultimate validation gate: server-side code
The accept
attribute is only a client-side enforcement, which can be bypassed. Therefore, to ensure file type validation, your server-side code should validate the file type during upload.
Setting up your file type filter options
Finding the right MIME type
Get the correct MIME for functionality from the IANA Media Types registry. Incorrect MIME types could mess up your filter, letting in unwanted file types.
Selecting multiple files
To enable users select multiple files, add the multiple
attribute to the <input>
tag. This is like asking your filter to work overtime!
The wildcard option
To broadly accept any file type, define your accept
value as "/". This can also be used as a placeholder until specific types are defined.
Extract the MIME type using JavaScript
The browser's File API allows you to retrieve a file's MIME type for additional validation before submission. However, remember this should not substitute server-side validation!
Was this article helpful?