Validating a file size in JavaScript while uploading

JavascriptWeb DevelopmentObject Oriented Programming

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

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<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>
<script>
   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’;
         }
      }
   }
</script>
</body>
</html>

Output

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


raja
Published on 16-Jul-2020 17:20:21
Advertisements