šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

Restrict image upload size with JavaScript

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *