Ensure an image upload is smaller than a specific size
By Flavio Copes
Learn how to make sure an image upload stays under a size limit like 3MB by checking the files size in a React onChange handler and rejecting bigger files.
~~~
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.
So here’s what I did to implement this requirement in a React app, using the onChange event:
<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]))
}
}}
/>
Notice the 3 * 1000 * 1024 part: mixing 1000 and 1024 is easy to get wrong. KB and KiB are different things, and I made a byte size converter to sort that out.
~~~
Related posts about js: