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.