HTML accept Attribute
Description
The HTML accept
attribute is used to specify the types of files that the server accepts, essentially guiding users to select the correct file types when uploading files through an input element of type file
. This attribute can be added to an <input>
element with the attribute type="file"
to define which file types are permissible for upload. The value of the accept
attribute is a string that represents the file MIME types that can be submitted through the input field. It can include specific file type specifiers, like "image/png" or "image/jpeg", and/or file extension specifiers, like ".png" or ".jpg". Multiple values can be included by separating them with a comma.
For example, to create a file input that accepts JPEG and PNG images, you would use the following HTML:
<input type="file" accept="image/jpeg, image/png">
This not only helps in filtering the files displayed in the file selection dialog of the user's operating system, making it easier for users to choose an appropriate file, but it also acts as a first layer of validation on the client side to ensure that files of incorrect types are not uploaded. However, it's important to note that the accept
attribute should not be relied upon as the sole method of validation for file uploads, as it can be bypassed; server-side validation of file types is also crucial for security and data integrity.
Syntax
<input accept="file_extension | audio/* | video/* | image/* | media_type">
Values
- file_extensionfile extensions can be accepted in a variety of ways, such as:
- File extensions: You can directly list the file extensions separated by commas. For instance,
accept=".jpg,.jpeg,.png"
restricts uploads to image formats only. - MIME types: MIME types (Multipurpose Internet Mail Extensions) are more specific and can be used like
accept="image/jpeg"
for JPEG images oraccept="application/pdf"
for PDF files. - Wildcards: You can use the asterisk (
*
) as a wildcard to specify a broader range of file types. For example,accept="image/*"
accepts all image formats.
- File extensions: You can directly list the file extensions separated by commas. For instance,
Applies To
The accept
attribute can be used on the following html elements.
Example
<p>
<label for="image">Select an JPG or PNG file:</label>
<input type="file" id="image" accept=".jpg, .png" />
</p>
<p>
<label for="video">Select a video file:</label>
<input type="file" id="video" accept="video/*" />
</p>
<p>
<label for="text">Select all Text files:</label>
<input type="file" id="text" accept=".txt" multiple />
</p>
Browser Support
The following table will show you the current browser support for the HTML accept
Attribute.
Desktop | |||||
12 | 1 | 1 | 12.1 | 1 |
Tablets / Mobile | |||||
18 | 4 | 12.1 | 1 | 1 | 4.4 |
Last updated by CSSPortal on: 25th March 2024