我正在构建一个允许用户创建营地并对其进行编辑的应用程序。最近我添加了上传图片功能,该功能可与创建路线配合使用,但在编辑路线上,它不允许用户将其留空碰巧会出现不确定的错误。您对我的解决方法有任何想法。我经验不足,因此欢迎您提供任何帮助。
这是js代码
var express = require("express");
var router = express.Router({mergeParams:true});
var Campground = require("../models/campground");
var middleware=require("../middleware");
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
const now = new Date().toISOString(); const date = now.replace(/:/g, '-'); cb(null, date + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
//edit
router.get("/:id/edit",middleware.checkCampgroundOwnership, function(req,res){
Campground.findById(req.params.id,function(err,foundCampground){
res.render("campgrounds/edit",{campground :foundCampground});
});
});
router.put("/:id",upload.single('image'),middleware.checkCampgroundOwnership, function(req,res){
var name = req.body.name;
var image = req.file.path;
var description = req.body.description;
var price = req.body.price
var upCampground = {price:price,name:name, image: image ,description:description};
Campground.findByIdAndUpdate(req.params.id,upCampground,function(err,updatedCamp){
if(err){
res.redirect("/campgrounds");
}
else{
res.redirect("/campgrounds/"+req.params.id);
}
})
});
这是ejs之一
<%-include ('../partials/header') %>
<div class="container">
<h1 style="text-align: center;"> Edit a <%= campground.name%></h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/campgrounds/<%=campground._id%>?_method=PUT" enctype="multipart/form-data" method="POST">
<div class="form-group">
<input class="form-control" type="text" name="name" value="<%= campground.name%>">
</div>
<div class="form-group">
<input class="form-control" type="number" name="price" value="<%= campground.price%> min="0.01" step="0.01"">
</div>
<div class="form-group">
<input class="form-control" type="file" name="image" value="\<%= campground.image%>">
</div>
<div class="form-group">
<input class="form-control" type="text" name="description" value="<%= campground.description %>">
</div>
<div class="form-group">
<button class="btn btn-primary btn-large btn-block">Submit</button>
</div>
</form>
<a href="/campgrounds">Go back</a>
</div>
</div>
<%-include ('../partials/footer') %>