这是我的multer代码
app.post('/addProduct', function(req, res){
upload(req,res,(err)=>{
if(err){
res.render('addproduct',{
mesg: err
});
}
new product({
_id: new mongoose.Types.ObjectId(),
image:req.body.image,
name: req.body.name,
price: req.body.price,
description: req.body.description,
category: req.body.category,
}).save(function(err)
{
if(err){
console.log(err);
res.render('addProduct')
}else{
res.redirect('/products');
}
})
});
})
//all function for uploading images and checking file
//storage engine
const storage= multer.diskStorage({
destination: './Public/images/',
filename: function(req, file, cb){
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
//upload method
const upload = multer({
storage: storage
}).single('image');
};
这是用于从./public/image文件夹中获取文件的代码
<div class= "two row">
<% products.forEach(product => { %>
<div class="column">
<img src="./Public/images/<%req.files[0].filename%>" class="cover-img">
<p><%= product.name %></p>
<h3>$<%= product.price %></h3>
<!--- <p><%= product.description %></p>-->
</div>
<% }); %>
addProduct.ejs代码
<div class= "two row" onclick="">
<% products.forEach(product => { %>
<div class="column">
<img src="/images/<%req.files[0].filename%>" class="cover-img">
<p><%= product.name %></p>
<h3>$<%= product.price %></h3>
<a action="/products/productId"></a><button class="btn">Add to cart</button></a>
<!--- <p><%= product.description %></p>-->
</div>
<% }); %>