Home > Net >  how do I make the image field required in node.js with postman
how do I make the image field required in node.js with postman

Time:11-05

If I uncheck the image field in Postman I need to display the error message in response instead of successful upload. how to do that?

Multer functionality

const storage = multer.memoryStorage();

fileFilter = (req, file, cb, res) => {
  if (
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpeg" ||
    file.mimetype === "image/heic"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
    return cb(new Error(".JEG/.PNG/.JPEG/.HEIC file are only allwored"));
   }
};

const maxSize = 1024 * 1024 * 2;

const upload = multer({
  storage: storage,
  limits: { fileSize: maxSize },
  fileFilter: fileFilter,
});
const uploads = upload.single("image");

POST method

router.post("/add_profile", async (req, res) => {
uploads(req, res, (err) => {
  if (err instanceof multer.MulterError) {
    return send(res, RESPONSE.FILE_TOO_LARGE);
  } else if (err) {
    return res.status(400).send(err.message);
  }
    try {
      const uploadData = new SomeModel({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        phone: req.body.phone,
        email: req.body.email,
        image: data.Location,
      });
    await uploadData.save();
      return send(res, RESPONSE.SUCCESS);
    } catch (err) {
      res.status(400).send(err.message);
    }
  });
});

here I unchecked the image field and sent the request it will work fine but I want to display the error like image field is required when I unchecked the image field enter image description here

CodePudding user response:

router.post("/add_profile", async (req, res) => {
        uploads(req, res, (err) => {
                    if (!req.file) {
                        return send(res, "Image is required!);
                    }
                    if (err instanceof multer.MulterError) {
                        return send(res, RESPONSE.FILE_TOO_LARGE);
                    } else if (err) {
                        return res.status(400).send(err.message);
                    }
                    try {
                        const uploadData = new SomeModel({
                            first_name: req.body.first_name,
                            last_name: req.body.last_name,
                            phone: req.body.phone,
                            email: req.body.email,
                            image: data.Location,
                        });
                        await uploadData.save();
                        return send(res, RESPONSE.SUCCESS);
                    } catch (err) {
                        res.status(400).send(err.message);
                    }
                });
        });
  • Related