multer.single 没有将输入文件上传到 req

multer.single dosen't upload inout file to req

我有一个表单,它有一个文件输入,用户必须使用它上传图像。 我正在使用 Multer 来处理这个问题,但出于某种原因,它工作得不太好 这是我的多重配置:

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();
});

这是我的路由器处理程序:

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

这是我在 PUG 语法中的形式:

    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")

嗯,我忘了将我的表单设置为多部分表单:) 该死的,我是多么菜鸟