Ensure an image upload is smaller than a specific size

By

Published · Updated

Tagged: JavaScript

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.

file.size is the size in bytes, so the limit has to be in bytes too.

Image Resizer & Compressor

Resize and compress images right in the browser with before/after sizes — files never get uploaded anywhere.

Image resizer & compressorInteractive · runs in your browser

Drop image(s) here or click to select

JPEG, PNG, WebP — multiple files supported

Processing…

Without React

The same check works in plain JavaScript. Instead of an alert(), I like to use the browser’s built-in validation message with setCustomValidity(). It shows the error next to the field and blocks the form from submitting:

<form>
  <input name="image" type="file" accept="image/*" />
  <button>Upload</button>
</form>

<script>
  const maximumSize = 3 * 1024 * 1024
  const input = document.querySelector('input[name="image"]')

  input.addEventListener('change', () => {
    const file = input.files[0]

    if (file && file.size > maximumSize) {
      input.setCustomValidity('Maximum size allowed is 3 MiB')
    } else {
      input.setCustomValidity('')
    }

    input.reportValidity()
  })
</script>

Don’t forget the else branch. As long as the message is not an empty string, the field stays invalid and the form won’t submit, even after the person picks a smaller file.

Checking multiple files

With the multiple attribute, input.files holds every selected file. Loop over it and check each one. You might also want a limit on the total:

const files = [...input.files]

const tooBig = files.find((file) => file.size > maximumSize)
const total = files.reduce((sum, file) => sum + file.size, 0)

if (tooBig) {
  input.setCustomValidity(`${tooBig.name} is larger than 3 MiB`)
} else if (total > 10 * 1024 * 1024) {
  input.setCustomValidity('All files together must be under 10 MiB')
} else {
  input.setCustomValidity('')
}

Show the size in a readable way

If you tell people their file is too big, it helps to say how big it is. A small helper turns bytes into something readable:

function formatSize(bytes) {
  if (bytes < 1024) return `${bytes} bytes`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
  return `${(bytes / 1024 / 1024).toFixed(1)} MiB`
}

formatSize(4404019) //'4.2 MiB'

Check again on the server

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.

Here’s how I’d do it with Express and multer. The limits.fileSize option is in bytes, and a bigger file makes multer fail with a LIMIT_FILE_SIZE error:

import express from 'express'
import multer from 'multer'

const app = express()

const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 3 * 1024 * 1024, files: 1 }
})

app.post('/upload', upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No image uploaded')
  }
  res.send(`Got ${req.file.originalname}, ${req.file.size} bytes`)
})

app.use((err, req, res, next) => {
  if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') {
    return res.status(413).send('Maximum size allowed is 3 MiB')
  }
  next(err)
})

app.listen(3000)

A file over the limit gets a 413 Content Too Large response, and the route handler never runs.

To check the file signature, look at the first bytes of the file. Every PNG starts with the same 8 bytes, and every JPEG starts with FF D8 FF:

function isPngOrJpeg(buffer) {
  const png = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
  const jpeg = [0xff, 0xd8, 0xff]
  const startsWith = (bytes) => bytes.every((byte, i) => buffer[i] === byte)
  return startsWith(png) || startsWith(jpeg)
}

if (!isPngOrJpeg(req.file.buffer)) {
  return res.status(400).send('Only PNG and JPEG images are allowed')
}

Put that check inside the route, after the req.file check. For a full walkthrough of handling uploads, see file uploads in Node.js with Express.

Want me to talk about your product? You can sponsor this site.

Related posts about js: