Html: How to limit file upload to be only images?
To restrict file uploads to images, use the accept
attribute on an <input type="file">
element. Set it to image/*
for all image types, or specify formats like image/png, image/jpeg
.
Note: The accept
attribute narrows down the file selections to image files in the browser's file dialog.
Layered Security: Client + Server Side
Though the accept
attribute is valuable, client-side restrictions can be bypassed. Enhance the security by performing server-side validation. Inspect the uploaded file's MIME type on the server to ensure the uploaded content is a genuine image.
Immediate Visual Feedback via FileReader API
Users appreciate visual feedback. With FileReader API, you can read the contents of uploaded images and provide a preview. This allows the user to validate the file content before the upload.
Multiple Images Upload
The accept
attribute pairs well with the multiple
attribute — allowing users to upload multiple images simultaneously:
Enforcing MIME Type and Size Restrictions
In addition to checking the MIME type, you can verify the actual contents of the file using JavaScript to analyze the file's binary data. Besides, apply client-side file size validation to avoid overloading the server.
Visualization
Using the accept
attribute is like having a bouncer:
The bouncer only lets in images, no matter the form:
The accept
attribute is the club's dress code: Images Only! 🚫👔🚫👗
Polite Error Handling
Graceful error handling and providing clear feedback to the user in case of invalid file selection enhances user experience. One way to do this is by resetting the input field.
Extra Security: Server-Side Checks
Although accept
can be bypassed, implementing MIME type checks on the server side provides an additional security layer. These checks confirm that the uploaded file matches the declared content type.
Was this article helpful?