Validating a file size in JavaScript while uploading

Following is the code for validating a file size in JavaScript while uploading −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
<h1>Validating a file size while uploading</h1>
<input type="file" class="file" onchange="validateFile()" />
<div class="result"></div>
<h3>Upload a file using the above file input type</h3>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let fileEle = document.querySelector(".file");
   function validateFile() {
      if (fileEle.files.length) {
         let fileSize = Math.round(fileEle.files[0].size / 1024);
         if (fileSize > 4096) {
            resEle.innerHTML = "File cant be uploaded too big";
         } else {
            resEle.innerHTML = "File can be uploaded. File size = " + fileSize+’ bytes’;


On clicking the ‘Choose file’ button and choosing a file −