所以我和multer有个问题,我想不出来。当我添加带有图像的项目时,一切正常,但如果我尝试添加没有图像的项目,则会失败。我有一个if语句,它将定义一个默认映像if req。文件未定义,但失败,错误为req。文件文件名未定义。。。这是代码
Multer设置:
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");
路线:
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");
});
});
});
});
所以我想我的问题是。。。如果没有选择图像,我将如何设置它不会失败?