Search code examples
node.jsexpressmulter

multer.single dosen't upload inout file to req


I have a form and it has a file input the user must upload an image using it. I'm using Multer for handling that but for some reason, it doesn't work quite well this is my multer config:

const multerStorage = multer.memoryStorage();
const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image")) {
    cb(null, true);
  } else {
    cb(
      res
        .status(401)
        .redirect(
          "/user/adminpanel/competitionform?error=Competition logo must be an image"
        ),
      false
    );
  }
};
const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter,
});
exports.uploadCompetitionLogo = upload.single("file");
//----------
exports.resizeAndSaveCompImages = catchAsync(async (req, res, next) => {
  if (!req.body.file) {
    return res
      .status(401)
      .redirect(
        "/user/adminpanel/competitionform?error=Each competition must have a logo"
      );
  }
  //generating teams logo name and saving it into the DB
  const competitionLogoFileName = `${Date.now()}-logo-${req.body.name.replace(
    " ",
    "-"
  )}.png`;

  await sharp(req.file.buffer)
    .toFormat("png")
    .resize(24, 24)
    .toFile(`static/images/competitions/${competitionLogoFileName}`);
  req.body.logo = competitionLogoFileName;
  next();
});

This is my Router handler:

    router.post(
  "/",
  compController.uploadCompetitionLogo,
  compController.resizeAndSaveCompImages,
  compController.createCompetition);

And this is my form in PUG syntax:

    form(action="/competitions",method="POST").flex
        input(type="text", name="name" placeholder="Competition name")
        span Competition logo
        div.flex    
            img(src="https://via.placeholder.com/150", alt="")#comp-logo
            input(type="file" name="file")#comp-file-input
        input(type="submit", value="Create competition")

Solution

  • Well, I forgot to set my form as a multipart form :) goddamn, how noob I am