Client Checking file size using HTML5

HTML5 provides a built-in File API that allows client-side file size checking without requiring Flash or server-side processing. This approach improves user experience by validating files before upload and provides immediate feedback to users.

The File API is part of the HTML5 specification and is supported by all modern browsers. It allows JavaScript to access file properties including name, size, type, and last modified date through the files property of file input elements.

Syntax

Following is the basic syntax to access file size using the File API −

var fileSize = document.getElementById('fileInput').files[0].size;

The files property returns a FileList object containing all selected files. Each file object has properties like size (in bytes), name, type, and lastModified.

Basic File Size Checking

To check if the File API is supported and access file size, use the following approach −

Example

<!DOCTYPE html>
<html>
<head>
   <title>Check File Size - Basic</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Select a File to Check Size</h2>
   <input type="file" id="myfile">
   <button onclick="checkFileSize()">Check Size</button>
   <p id="result"></p>
   
   <script>
      function checkFileSize() {
         if (typeof FileReader !== "undefined") {
            var fileInput = document.getElementById('myfile');
            if (fileInput.files.length > 0) {
               var fileSize = fileInput.files[0].size;
               var fileName = fileInput.files[0].name;
               document.getElementById('result').innerHTML = 
                  "File: " + fileName + "<br>Size: " + fileSize + " bytes";
            } else {
               document.getElementById('result').innerHTML = "Please select a file first.";
            }
         } else {
            document.getElementById('result').innerHTML = "File API not supported in this browser.";
         }
      }
   </script>
</body>
</html>

This example checks if the File API is supported using typeof FileReader !== "undefined" and then displays the selected file's name and size in bytes.

Real-time File Size Checking with Event Listener

For better user experience, check file size automatically when a file is selected using the onchange event listener −

Example

<!DOCTYPE html>
<html>
<head>
   <title>Real-time File Size Check</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>File Size Checker</h2>
   <input type="file" id="fileInput" accept=".jpg,.png,.pdf,.doc,.txt">
   
   
   <script>
      document.getElementById('fileInput').onchange = function() {
         var fileInput = this;
         var fileInfo = document.getElementById('fileInfo');
         
         if (fileInput.files.length > 0) {
            var file = fileInput.files[0];
            var sizeInBytes = file.size;
            var sizeInKB = (sizeInBytes / 1024).toFixed(2);
            var sizeInMB = (sizeInBytes / (1024 * 1024)).toFixed(2);
            
            fileInfo.innerHTML = 
               "<strong>File Selected:</strong><br>" +
               "Name: " + file.name + "<br>" +
               "Size: " + sizeInBytes + " bytes (" + sizeInKB + " KB, " + sizeInMB + " MB)<br>" +
               "Type: " + file.type + "<br>" +
               "Last Modified: " + new Date(file.lastModified).toLocaleDateString();
         } else {
            fileInfo.innerHTML = "No file selected.";
         }
      };
   </script>
</body>
</html>

This example automatically updates file information when a file is selected, showing size in bytes, KB, and MB formats along with other file properties.

File Size Validation with Limits

A practical use case is validating file size against predefined limits before allowing upload −

Example

<!DOCTYPE html>
<html>
<head>
   <title>File Size Validation</title>
   <style>
      .success { color: green; font-weight: bold; }
      .error { color: red; font-weight: bold; }
      .file-input { margin: 10px 0; }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>File Upload with Size Validation</h2>
   <p>Maximum file size allowed: <strong>2 MB</strong></p>
   
   <input type="file" id="uploadFile" class="file-input">
   
   <button id="uploadBtn" disabled style="margin-top: 10px;">Upload File</button>
   
   <script>
      const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 MB in bytes
      
      document.getElementById('uploadFile').onchange = function() {
         var file = this.files[0];
         var validationDiv = document.getElementById('validation');
         var uploadBtn = document.getElementById('uploadBtn');
         
         if (file) {
            var fileSizeInMB = (file.size / (1024 * 1024)).toFixed(2);
            
            if (file.size <= MAX_FILE_SIZE) {
               validationDiv.innerHTML = 
                  '<span class="success">? File size OK: ' + fileSizeInMB + ' MB';
               uploadBtn.disabled = false;
            } else {
               validationDiv.innerHTML = 
                  '<span class="error">? File too large: ' + fileSizeInMB + ' MB. Maximum allowed: 2 MB';
               uploadBtn.disabled = true;
            }
         } else {
            validationDiv.innerHTML = '';
            uploadBtn.disabled = true;
         }
      };
      
      document.getElementById('uploadBtn').onclick = function() {
         alert('File ready for upload!');
      };
   </script>
</body>
</html>

This example validates the file size against a 2MB limit, shows appropriate success or error messages, and enables/disables the upload button accordingly.

Multiple File Size Checking

When dealing with multiple file selection, you can check the size of all selected files −

Example

<!DOCTYPE html>
<html>
<head>
   <title>Multiple Files Size Check</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Multiple File Size Checker</h2>
   <input type="file" id="multipleFiles" multiple>
   
   
   
   <script>
      document.getElementById('multipleFiles').onchange = function() {
         var files = this.files;
         var filesList = document.getElementById('filesList');
         var totalSizeDiv = document.getElementById('totalSize');
         var totalSize = 0;
         
         if (files.length > 0) {
            var filesInfo = '<h3>Selected Files:</h3><ul>';
            
            for (var i = 0; i < files.length; i++) {
               var file = files[i];
               var sizeInKB = (file.size / 1024).toFixed(2);
               totalSize += file.size;
               
               filesInfo += '<li>' + file.name + ' - ' + sizeInKB + ' KB</li>';
            }
            
            filesInfo += '</ul>';
            filesList.innerHTML = filesInfo;
            
            var totalSizeInMB = (totalSize / (1024 * 1024)).toFixed(2);
            totalSizeDiv.innerHTML = 'Total Size: ' + totalSizeInMB + ' MB (' + files.length + ' files)';
         } else {
            filesList.innerHTML = '';
            totalSizeDiv.innerHTML = '';
         }
      };
   </script>
</body>
</html>

This example handles multiple file selection, displays individual file sizes, and calculates the total size of all selected files.

File API Properties File Object file.name File name file.size Size in bytes file.type MIME type Size Conversion Bytes file.size KB size / 1024 MB size / (1024*1024) Browser Support ? Chrome 6+ ? Firefox 3.6+ ? Safari 6+ ? IE 10+ ? Edge (all)

Browser Compatibility

The File API is widely supported across modern browsers. For older browser support, always check if FileReader is available before accessing file properties. The API works consistently in Chrome 6+, Firefox 3.6+, Safari 6+, Internet Explorer 10+, and all versions of Edge.

Key Points

  • Always check for File API support using typeof FileReader !== "undefined" before accessing file properties.

  • The size property returns file size in bytes. Convert to KB or MB for better user readability.

  • Use the onchange event for real-time file validation as users select files.

  • For multiple files, iterate through the files array to check each file individually.

  • File size checking happens on the client side, providing immediate feedback without server requests.

Conclusion

HTML5's File API provides a robust solution for client-side file size checking without requiring Flash or server-side processing. By using the files property and event listeners, you can validate file sizes in real-time and improve user experience with immediate feedback before file uploads.

Updated on: 2026-03-16T21:38:53+05:30

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements