Q. How do I validate file types, restrict to images only, and prevent malicious uploads?

A:
Use a fileFilter function in Multer config:

fileFilter: (req, file, cb) => {

  const allowed = /jpeg|jpg|png|gif/;

  const ext = path.extname(file.originalname).toLowerCase();

  if (allowed.test(ext) && allowed.test(file.mimetype)) {

    cb(null, true);

  } else {

    cb(new Error(‘Only image files allowed’));

  }

}

 

Also set limits: { fileSize: maxBytes } to prevent overly large uploads. Sanitize filenames, avoid path traversal attacks, and store uploads in non-executable directories. After upload, verify the file’s MIME type via inspecting magic bytes if needed.

Back To Top