Validate File Size Before Upload with JavaScript

OpenJavaScript 0

Last updated: February 12, 2023.

You can use JavaScript to validate the size of a user-selected file before it is uploaded.

Doing so minimizes requests made to the server containing files that do not meet file size requirments.

Typically, the requirment will be that the file should be less than a certain size.

It is generally a good idea to do validation in a dedicated function, which can be called any time during the file upload process.

The following function checks if a file selected via an <input> element exceeds 2 MB:

function validateSize() {
    const file = document.querySelector('input').files[0]; 
    // Gets file from input element
    if (!file) {
        // Runs if no file selected
        alert("Error: You need to select a file");
        throw new Error("No file");
    }
    const limit = 2000; // Sets size limit in KB
    const size = Math.round(file.size/1024); // Converts file size from bytes to KB
    if (size < limit) {
        alert(`File size OK: ${size} bytes`);
    } else {
        alert(`Error: File larger than 2MB (${(size/1000).toFixed(2)} MB)`);
        throw new Error(`File too large: ${size} bytes`);
    }
}

The next example shows how the function can be called in practice.

The validateSize function is called 'live', whenever a file is selected by the user, and when the user attempts to submit the form:

<form>
  <label for="fileInput">Select file (limit 2 MB):</label><br>
  <input type="file" id="fileInput">
  <button type="submit">Submit</button>
  <span id="info"></span>
</form>
<script>
  const input = document.querySelector('input');
  input.addEventListener('change', () => {
    validateSize();
  })
  document.querySelector('form').addEventListener('submit', (e) => {
    e.preventDefault(); // Prevents default HTML submission
    validateSize(); // Checks file size
    // Optionally add more validation functions
    alert("Uploading..."); // Add code to upload file here
  });
  function validateSize() {
    const file = document.querySelector('input').files[0];
    if (!file) {
        alert("Error: You need to select a file");
        throw new Error("No file");
    }
    const limit = 2000;
    const size = Math.round(file.size/1024);
    if (size < limit) {
        alert(`File size OK: ${size} bytes`);
    } else {
        alert(`Error: File larger than 2MB (${(size/1000).toFixed(2)} MB)`);
        throw new Error(`File too large: ${size} bytes`);
    }
  }
</script>

Note that although client-side validation like this will prevent a file that is too large from being uploaded in many cases, it is possible for a user to circumvent any validation you add in the client.

Client-side file size validation should therefore be complementary to and not a substitute for server-side validation.

Related posts