1.edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
img{
width: 30px;
}
</style>
</head>
<body>
<form action="/doEdit" method="post" role="form" enctype="multipart/form-data">
<legend>添加成员</legend>
<input type="hidden" value="{{@data._id}}" name="id">
<div class="form-group">
<label for="">服装名称</label>
<input type="text" name="shopname" value="{{data.shopname}}" class="form-control" id="" placeholder="请输入服装名称">
</div>
<div class="form-group">
<label for="">服装价格</label>
<input type="text" name="price" value="{{data.price}}" class="form-control" id="" placeholder="请输入服装价格">
</div>
<div class="form-group">
<label for="">服装销量</label>
<input type="text" name="shopNumber" value="{{data.shopNumber}}" class="form-control" id="" placeholder="请输入服装销量">
</div>
<div class="form-group">
<label for="">上传图片</label>
<img src="{{data.avatar}}" alt="">
<input type="file" name="file" >
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
</body>
</html>
2.edit.js
const Router = require("koa-router");
const router = new Router();
const ShopMangeModel = require("../models/shopMange");
// 查询数据库
router.get("/edit",async ctx=>{
var {id} = ctx.query;
var data = await ShopMangeModel.findOne({_id:id});
console.log(data);
await ctx.render("edit",{data:data})
})
module.exports = router;
3.doEdit.js
const router = require("koa-router")();
const path = require("path");
const ShopMangeModel = require("../models/shopMange");
// 查询数据库
const fileUpload = require("../utils/upload");
router.post("/doEdit", async ctx => {
console.log(ctx.request.files);
var file = ctx.request.files.file;
var uploadName = path.basename(file.path);
var isUpload = Boolean(file.name.trim());
var {id,shopname,price,shopNumber} = ctx.request.body;
var data = ({
shopname,
price,
shopNumber
})
/* 将本地图片放到服务器的static文件夹中 */
if (isUpload) {
fileUpload(file.path, uploadName);
var avatar = ctx.origin + "/" + uploadName;
data.avatar = avatar;
}
await ShopMangeModel.updateOne({ _id: id},data)
ctx.redirect("/")
})
module.exports = router;