Explain Codes LogoExplain Codes Logo

Limit the size of a file upload (html input element)

html
file-upload
client-side-validation
server-side-verification
Anton ShumikhinbyAnton Shumikhin·Nov 8, 2024
TLDR

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:

document.querySelector('#fileUpload').onchange = function() { if (this.files[0].size > 1048576) { // User tried to upload a file larger than 1MB: 1024 * 1024 alert('Trying to upload an elephant? Choose a file smaller than 1MB, please.'); // Indirectly saying "We don't host elephants here". Everyone will get the hint. ;) this.value = ''; } };

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:

<input type="hidden" name="MAX_FILE_SIZE" value="1048576" /> <!-- Limitating to 1MB -->

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:

let list = document.querySelector('#fileList'); let fileInput = document.getElementById('fileUpload'); fileInput.addEventListener('change', function() { let files = fileInput.files; let message = "Files without extra weight:\n"; for (let i = 0; i < files.length; i++) { if (files[i].size > 1048576) { alert(`File ${files[i].name} is too large and didn't pass the weight-check. Better luck next time!`); } else { message += `${files[i].name} (${(files[i].size / 1024 / 1024).toFixed(2)} MB)\n`; } } list.textContent = message; });

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:

<input type="file" accept=".jpg,.png" />

This filter reduces the risk of harmful files. Remember though, never trust client-side validation alone!