HTML < input> accept Attribute
Last Updated :
17 Apr, 2025
Improve
The HTML <input> accept attribute is used to control the type of files that can be selected for input, restricting the file selection to specific formats such as image/* for images or .pdf for PDF files.
Syntax:
<input accept = "file_extension | audio/* | video/* | image/* | media_type">
<html>
<body>
<form>
<label for="fileUpload">Upload an image file:</label>
<input type="file" id="fileUpload" name="fileUpload" accept="image/*">
<input type="submit" value="Submit">
</form>
</body>
</html>
- The accept=”image/*” attribute restricts the file input to accept only image files, enhancing user experience by filtering selectable files in the dialog.
- The <input type=”file”> element allows users to browse and select files from their device for upload.
Attribute Values:
Value | Description |
---|---|
file_extension | Specify the file extension(s) like .gif, .jpg, .png, .doc) the user can pick from. |
audio/* | The user can pick all sound files. |
image/* | A valid media type, with no parameters. Look at IANA Media Types for a complete list of standard media types. |
media_type | A valid media type without parameters. |
More example of HTML <input> accept Attribute
HTML <input> accept Attribute
<html >
<body>
<form>
<label for="imageUpload">Upload an image (JPEG or PNG):</label>
<input type="file" id="imageUpload" name="imageUpload" accept=".jpeg, .jpg, .png">
<input type="submit" value="Submit">
</form>
</body>
</html>
- The accept attribute is set to .jpeg, .jpg, .png, allowing users to select image files with these specific extensions.
- This ensures that only JPEG and PNG images can be selected for upload.
Styled File Input for PDF Documents
<html>
<head>
<style>
.file-input {
display: inline-block;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
}
.file-input:hover {
background-color: #45a049;
}
#pdfUpload {
display: none;
}
</style>
</head>
<body>
<form>
<label for="pdfUpload" class="file-input">Choose a PDF file</label>
<input type="file" id="pdfUpload" name="pdfUpload" accept="application/pdf">
<input type="submit" value="Submit">
</form>
</body>
</html>
- The file input is styled to appear as a button labeled “Choose a PDF file,” enhancing the user interface.
- The accept attribute is set to application/pdf, restricting file selection to PDF documents only.
Best Practices for Using the HTML <input> accept Attribute:
- Specify Exact File Types: Clearly define acceptable file types using MIME types or file extensions to guide users in selecting appropriate files.
- Implement Server-Side Validation: While the accept attribute provides a hint to users, always validate the file type on the server to ensure security and proper handling.
- Provide User Instructions: Offer clear guidance or labels indicating the types of files accepted to enhance user experience and reduce errors.