Back to results for “Media”
Node.js › File Uploads & Media Processing

How would you validate an uploaded image's actual dimensions and reject ones that don't meet minimum or maximum size requirements?

Intermediate

Answer

After the file is uploaded (but before accepting it as valid), you can use an image-processing library like sharp to read the image's actual metadata (width and height) and compare it against your application's requirements, rejecting and cleaning up the uploaded file if it doesn't meet the criteria, rather than relying solely on file-size limits which don't reflect actual image dimensions.
const sharp = require('sharp');

const metadata = await sharp(req.file.path).metadata();
if (metadata.width < 200 || metadata.height < 200) {
  await fs.promises.unlink(req.file.path); // clean up the rejected upload
  return res.status(400).json({ error: 'Image must be at least 200x200 pixels' });
}
Real-world example A profile-picture upload feature rejects images smaller than 200x200 pixels after checking the actual decoded image metadata with sharp, cleaning up the temporarily-saved file immediately rather than leaving rejected uploads accumulating on disk.

Common follow-ups: Why is checking actual image dimensions via a library more reliable than trying to infer size from file size alone?;What's an appropriate cleanup strategy for uploaded files that fail validation, to avoid accumulating orphaned files over time?