Limit the size of a file upload (html input element)
The client-side file size limit on <input type="file">
is enforced using JavaScript. After attaching a change
event listener to the input and the user selected a file, file size will be checked and an alert prompted if the file size is oversized. Here is the basic code:
Server-side validation is a security essential. Use <input type="file" id="fileUpload">
for the HTML part.
Handling older browsers
For the Jurassic park browsers, not everyone has access to HTML5 File API. For these dinosaur browsers like IE7+, we favor a fallback option such as Flash or Silverlight, or promote an upgrade to a more recent browser. In IE9
, we can still utilize the files
attribute, but the size
validation differs.
In the absence of a hard limit, showcasing feedback to users about how to compress files, or split humongous documents, is a huge leap in enhancing user experience. Informing users about the maximum file size prior to upload can reduce disappointment.
Server-side checks
Be aware: your client-side script could be side-stepped, with or without intent. Hence, it's prudent to have a server-side verification in position. Adding a hidden
field named MAX_FILE_SIZE
lets you signalize to the server about the maximum file size allowed:
As the hidden
field can be manipulated or overlooked, the server should verify the file size after receipt. No free lunches here!
Cross-platform testing
Whilst our JS solution has been made compatible with modern browsers, ensuring cross-browser compliance is paramount. The client-side solution needs rigorous testing on IE7+, Chrome, and Firefox 3.6+.
Tools like jsfiddle or CodePen come in handy here to develop live examples. Besides, it offers insights into the user experience across various devices and conditions.
Showing file list
List out all selected files and their sizes before submission to facilitate user review. Flag oversized files, report them as rejected to the user, and remove them from the selection:
Keeping users in the loop is essential, so they know what's happening if their files aren't going through.
User guidance
Whenever users try to upload oversized files, present them with detailed instructions on what to do next. Whether it includes compressing their files or splitting them into smaller modules, clear information will help them work within the size constraints.
Security precautions
On the client-side, validate file sizes and types to prevent most improper uploads. Use the accept
attribute on your file input to impose additional restrictions on file types:
This filter reduces the risk of harmful files. Remember though, never trust client-side validation alone!
Was this article helpful?