Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validating a file size in JavaScript while uploading
Following is the code for validating a file size in JavaScript while uploading −
Example
<!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 −

Advertisements