How to: Check File Upload Size with JavaScript

How to: Check File Upload Size with JavaScript

Uploading files to a website is a common feature that is often used for uploading images, videos, and documents. However, you may want to limit the size of the files that can be uploaded, to prevent your server from becoming overwhelmed with large files. Fortunately, JavaScript provides an easy way to check the size of a file before it’s uploaded.

First, let’s create an HTML form for the user to upload their file. Here’s an example:

<form>
  <input type="file" id="fileInput">
  <button type="button" onclick="checkFile()">Upload File</button>
</form>

This form includes an input field of type “file” and a button to trigger the file upload. We’ve also added an id of “fileInput” to the input field so that we can easily reference it in our JavaScript code.

Next, let’s write the JavaScript function to check the size of the file. Here’s an example:

function checkFile() {
  const fileInput = document.getElementById('fileInput');
  const fileSize = fileInput.files[0].size;
  const maxSize = 1024 * 1024; // 1MB

  if (fileSize > maxSize) {
    alert('File size must be less than 1MB');
  } else {
    // Upload the file
  }
}

In this function, we first get the file input element using its id. Then, we get the size of the file that the user selected by accessing the “files” property of the input element and retrieving the first file in the array.

Next, we set a maximum file size by declaring a constant called “maxSize” and setting it to 1MB (1024 * 1024 bytes).

Finally, we check if the file size is greater than the maximum size. If it is, we display an alert to the user telling them that the file size must be less than 1MB. If the file size is within the limit, we can proceed with uploading the file.

And there you have it! With just a few lines of JavaScript, you can easily check the size of a file before it’s uploaded to your website. This is just one example of the many ways you can use JavaScript to add interactivity and functionality to your website. Enjoy!