Restrict file upload size using JavaScript

Restrict file upload size using JavaScript: Hey Folks! Do you want to limit file upload size on your web application? that too using JavaScript? If yes, perfect you are at right place. In this article we gonna discuss how to restrict file upload size using JavaScript.

Uploading files is a common feature in web applications. While it allows users to share their files with others or store them online, it can also pose a security risk to the application. One way to mitigate this risk is by restricting the file upload size. In this blog post, we will explore how to use JavaScript to limit the size of the files that can be uploaded to your web application. We will discuss the simple approach to achieve this, their pros and cons, and provide a step-by-step guide to implementing them. By the end of this post, you’ll have a better understanding of how to enhance the security of your web application by limiting the size of file uploads.

Restrict file upload size using JavaScript

How to Restrict file upload size using JavaScript

Let’s start with the HTML required to upload a file:

<form action="#" method="post" enctype="multipart/form-data">
  <h2>File Upload Form</h2>
  <h3>Max File Size is 1 MB</h3>
   <label for="file">Select a file to upload:</label>
   <br>
   <input type="file" id="file-input" name="file">
   <br>
   <p id="file-result"></p>
   <input id="file-submit" type="submit" disabled />
</form>

Here we have made submit button disabled initially. This will prevent user submitting the larger file size util we have checked the file size. Now lets add some style to give it a good looks as well 🙂

     form {
        max-width: 500px;
        margin: 0 auto;
      }
      input[type="file"] {
        margin-bottom: 10px;
      }
      input[type="submit"] {
        background-color: #4CAF50;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }
      input[type="submit"]:hover {
        background-color: #3e8e41;
      }
input[type="submit"]:disabled,
input[type="submit"][disabled]{
  border: 1px solid #999999;
  background-color: #cccccc;
  color: #666666;
}

Perfect now everything is ready. Its time to write some logic using JavaScript. Below is the JavaScript code for it.

let fileInput = document.getElementById("file-input");
let fileResult = document.getElementById("file-result");
let fileSubmit = document.getElementById("file-submit");

fileInput.addEventListener("change", function () {
  if (fileInput.files.length > 0) {
    const fileSize = fileInput.files.item(0).size;
    const fileMb = fileSize / 1024 ** 2;
    if (fileMb >= 1) {
      fileResult.innerHTML = "Please select a file less than 1 MB.";
      fileSubmit.disabled = true;
    } else {
      fileResult.innerHTML = "Success, your file is " + fileMb.toFixed(1) + "MB.";
      fileSubmit.disabled = false;
    }
  }
});

Here first of all we have declared some variables that reference the HTML elements. Then To limit the size of files that can be uploaded, we have used an event listener that triggers whenever the file input changes. This event is fired when a user selects a file. Once the file input changes, our script will run and verify the size of the selected file.

In case the selected file exceeds 1MB, we will keep the submit button disabled and inform the user to choose a smaller file size. Conversely, if the file size is less than or equal to 1MB, the submit button will be enabled and a success message will be displayed.

You can also look at our codepen for quick execution.

Code to Restrict file upload size using JavaScript

Conclusion

Limiting the size of file uploads is crucial for maintaining the security of your web application. By using JavaScript and the methods outlined in this post, you can easily control the size of files uploaded by users. So, next time you add a file upload feature, make sure to follow these steps and keep your application secure.

That’s it for this tutorial! With the knowledge gained, you should now be capable of limiting the size of file uploads using JavaScript. While you’re here, don’t forget to explore our diverse range of JavaScript tutorials.

Write for us
GeekyBeginners articles are written by software geeks like you. If you also would like to contribute to GeekyBeginners by writing paid articles, you can check the write for us page.

Leave a Comment