AI Workshop: learn to build apps with AI →
File APIs: Validating file size before upload

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


When accepting file uploads, you often need to limit the file size before sending the file to the server. The File object’s size property makes this straightforward.

Checking file size

The size property is in bytes. Example: validate a maximum size of 3 MB:

const input = document.querySelector('input[type="file"]')

input.addEventListener('change', (event) => {
  const file = event.target.files[0]
  
  if (!file) return
  
  const maxSize = 3 * 1024 * 1024 // 3 MB in bytes
  
  if (file.size > maxSize) {
    alert('Maximum size allowed is 3MB')
    event.target.value = '' // Clear the input
    return
  }
  
  // File is valid, proceed with upload
  console.log(`File "${file.name}" is ${file.size} bytes`)
})

React example

<input
  name='image'
  type='file'
  accept='image/*'
  onChange={(event) => {
    if (event.target.files && event.target.files[0]) {
      if (event.target.files[0].size > 3 * 1024 * 1024) {
        alert('Maximum size allowed is 3MB')
        return false
      }
      setImage(event.target.files[0])
      setImageURL(URL.createObjectURL(event.target.files[0]))
    }
  }}
/>

Size conversion helpers

const formatFileSize = (bytes) => {
  if (bytes < 1024) return bytes + ' bytes'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

// Usage
console.log(formatFileSize(file.size)) // "2.5 MB"

Client-side validation gives immediate feedback; also validate on the server, since client-side checks can be bypassed.

Lessons in this unit:

0: Introduction
1: The File object
2: FileList
3: FileReader
4: Blob
5: FormData
6: Accept only images in file input
7: Check if checkbox is checked
8: Reset a form
9: File upload with server handling
10: Drag and drop file upload
11: ▶︎ Validating file size before upload