Course contentsShow
← Web Development
Lesson 2697 of 2,98248. File Uploads and HandlingFree lesson

File Size Validation

Check file size limits before upload using the File API's size property to prevent oversized files.

File Size Validation

You'll learn how to check file sizes before uploading to prevent oversized files from consuming bandwidth and server resources.

Why Validate File Size?

Imagine a nightclub with a "no bags larger than this" rule—they check at the door, not after you've squeezed through the crowd. Similarly, validating file size before upload saves everyone time and bandwidth. Users get instant feedback, and your server doesn't waste resources processing files you'll reject anyway.

Using the File API's size Property

Every File object in JavaScript has a size property that returns the file size in bytes. You can check this immediately after the user selects a file, long before any upload begins.

const fileInput = document.getElementById('myFile');

fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  
  if (!file) return;
  
  const maxSizeInBytes = 5 * 1024 * 1024; // 5 MB
  
  if (file.size > maxSizeInBytes) {
    alert(`File too large! Maximum size is 5 MB. Your file is ${(file.size / 1024 / 1024).toFixed(2)} MB.`);
    fileInput.value = ''; // Clear the selection
    return;
  }
  
  // File size is acceptable, proceed
  console.log('File size OK:', file.size, 'bytes');
});

Size Conversions

Remember your byte math:

  • 1 KB = 1024 bytes
  • 1 MB = 1024 * 1024 bytes (1,048,576)
  • 1 GB = 1024 * 1024 * 1024 bytes

Always set sensible limits based on your application's needs—profile photos might cap at 2 MB, while documents could allow 10 MB.

Key Takeaway: Use the File object's size property to validate file sizes client-side before upload, providing immediate user feedback and preventing wasted bandwidth.