Ensure an image upload is smaller than a specific size
By Flavio Copes
Check an image file's size in a React file input for fast feedback, then repeat the validation on the server before accepting the upload.
~~~
I had a form with a file input box, to let people upload an image:
<input
name="image"
type="file"
accept="image/*"
/>
I needed this image to be smaller than 3MB.
Here is a client-side check in React:
const maximumSize = 3 * 1024 * 1024
<input
name="image"
type="file"
accept="image/*"
onChange={(event) => {
const file = event.currentTarget.files?.[0]
if (!file) return
if (!file.type.startsWith('image/')) {
alert('Choose an image file')
event.currentTarget.value = ''
return
}
if (file.size > maximumSize) {
alert('Maximum size allowed is 3 MiB')
event.currentTarget.value = ''
return
}
setImage(file)
}}
/>
3 * 1024 * 1024 is 3 MiB. If your product promises 3 MB in decimal units, use 3 * 1000 * 1000 instead. My byte size converter shows the difference.
The browser check is only a convenience. A user can bypass it and accept="image/*" only guides the file picker. Enforce the size limit again on the server, inspect the actual file signature instead of trusting the MIME type or extension, and reject the upload before storing it.
~~~
Related posts about js: