1.add.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">
</head>
<body>
<form action="/doAdd" method="post" role="form" enctype="multipart/form-data">
<legend>添加商品</legend>
<div class="form-group">
<label for="">服装名称</label>
<input type="text" name="shopname" class="form-control" id="" placeholder="请输入服装名称">
</div>
<div class="form-group">
<label for="">服装价格</label>
<input type="text" name="price" class="form-control" id="" placeholder="服装价格">
</div>
<div class="form-group">
<label for="">服装销量</label>
<input type="text" name="shopNumber" class="form-control" id="" placeholder="服装销量">
</div>
<div class="form-group">
<label for="">上传图片</label>
<input type="file" name="file">
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
</body>
</html>
2.add.js
const router = require("koa-router")();
// 查询数据库
router.get("/add",async ctx=>{
await ctx.render("add")
})
module.exports = router;
3.doAdd.js
const router = require("koa-router")();
const path = require("path");
const ShopMangeModel = require("../models/shopMange");
// 查询数据库
const fileUpload = require("../utils/upload");
router.post("/doAdd",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());
// console.log(uploadName);
// console.log(isUpload);
/* 将本地图片放到服务器的static文件夹中 */
if(isUpload){
fileUpload(file.path,uploadName);
var avatar = ctx.origin +"/"+uploadName;
var {shopname,price,shopNumber} = ctx.request.body;
console.log(ctx.request.body);
var data = new ShopMangeModel({
shopname,
price: Number(price),
shopNumber: Number(shopNumber),
avatar
})
data.save(err => {
if (err) {
throw err
};
})
}
ctx.redirect("/")
})
module.exports = router;