Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026
The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.
When accepting file uploads, you often need to limit the file size before sending it to the server. The File object’s size property makes this straightforward.
Checking file size
The size property returns the file size in bytes. Here’s how to validate a maximum size of 3MB:
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 // 3MB 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 * 1000 * 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 improves user experience by providing immediate feedback, but always validate on the server too since client-side checks can be bypassed.