Darrell
Darrell

Reputation: 29

issue with multer not allowing a default image

So I am having an issue with multer that i can't figure out. When I add an item with an image everything works with no issues but if I try to add an item with no image it fails. I have an if statement that will define a default image if req.file is undefined but it fails with the error saying req.file.filename is undefined ... Here is the code

Multer setup:

var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, "./public/uploads");
  },
  filename: function(req, file, callback) {
    callback(null, Date.now() + file.originalname);
  }
});
var upload = multer({ storage: storage }).single("file");

route:

router.post("/item/add", middleware.isLoggedIn, (req, res) => {
  User.findById(req.user._id, (err, user) => {
    upload(req, res, err => {
      if (err) {
        req.flash("error", "failed to upload file");
        return res.redirect("/products");
      }
      var item = new Item();
      item.name = req.body.name;
      item.description = req.body.description;
      item.price = req.body.price;
      item.createdBy = { id: req.user._id, username: req.user.username };
      if (typeof req.file === undefined) {
        item.image = "/uploads/no-img.png";
      } else {
        item.image = "/uploads/" + req.file.filename;
      }
      item.save(function(err) {
        if (err) {
          res.send(err);
        }
        return res.redirect("/products");
      });
    });
  });
});

So I guess my question is... How would I set this up where it wont fail with no image selected?

Upvotes: 1

Views: 891

Answers (1)

Vasan
Vasan

Reputation: 4956

Your problem is here:

if (typeof req.file === undefined) {

typeof returns a string.

Your check should be if (typeof req.file === "undefined") {

Upvotes: 3

Related Questions