After posting the article about how to invert the colors of an image with Javascript I received a question regarding whether it is possible to limit the size of the uploaded file image.
So here it goes!
Let's say that we have the following HTML input to upload an image:
<p>IMG FILE MAX SIZE = 1MB</p>
<input id="inp" type='file' accept='image/*' capture='camera'/>
We want to limit the size of this image to a maximum of 1MB.
Reading the uploaded image size with Javascript
The first step will be to read the uploaded image size. This can easily be done with the .size attribute of an uploaded file:
input.addEventListener('change', () => {
const {files} = input
if (files.length > 0) {
const fileSize = files.item(0).size
const fileMb = fileSize / 1024 ** 2
alert(fileMb)
}
})
Limiting uploaded image size to 1MB
And now that we have the size of the uploaded image we can just do a simple check to limit the maximum accepted size:
const input = document.querySelector('#inp')
const MAX_IMG_SIZE = 1
input.addEventListener('change', () => {
const {files} = input
if (files.length > 0) {
const fileSize = files.item(0).size;
const fileSizeMb = fileSize / 1024 ** 2;
if (fileSizeMb > MAX_IMG_SIZE) {
alert(`Too big! Select an image under ${MAX_IMG_SIZE} MB!`)
input.value = ""
return false
}
}
})
If the image size is above the MAX_IMG_SIZE we will reset the HTML file input and return false.
You can check out the full code for the example in this codepen.
As a closing thought please note that you can never fully rely only on the client-side Javascript validation. You will also need to double-check the image file size on the backend.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js