B
B
Bogdan2019-05-13 16:29:22
Node.js
Bogdan, 2019-05-13 16:29:22

Multer checking for file parameter?

Hello, but can you tell me how to properly validate in multer, what if there is no file parameter, give an error?

const fileFilter = async (req, file, next) => {
 ...
  return next(null, true);
};

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, pathGalleryCategories),
  filename: (req, file, cb) => cb(null, req.categoryId.toString())
});

const upload = multer({
  fileFilter,
  storage
});

routes.post('', upload.single('file'), (req, res) => {
  res.json({ id: req.categoryId });
});

It turns out that if you do not set the file parameter , then middlware upload.single('file') -> fileFilter does not work at all .
How to properly check? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2019-05-13
@bogdan_uman

Add another middleware or wrap multer in a middleware

routes.post('',
  upload.single('file'),
  (req, res, next) => {
    next(req.file ? null : new Error('No file!'));
  },
  (req, res) => {
    res.json({ id: req.categoryId });
  }
);

or
routes.post('',
  (req, res, next) => {
    upload.single('file')(req, res, (err) => {
      if (err) return next(err);
      if (!req.file) return next(new Error('No file!'));
      next();
    });
  },
  (req, res) => {
    res.json({ id: req.categoryId });
  }
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question