1.add.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
  9. </head>
  10. <body>
  11. <form action="/doAdd" method="post" role="form" enctype="multipart/form-data">
  12. <legend>添加商品</legend>
  13. <div class="form-group">
  14. <label for="">服装名称</label>
  15. <input type="text" name="shopname" class="form-control" id="" placeholder="请输入服装名称">
  16. </div>
  17. <div class="form-group">
  18. <label for="">服装价格</label>
  19. <input type="text" name="price" class="form-control" id="" placeholder="服装价格">
  20. </div>
  21. <div class="form-group">
  22. <label for="">服装销量</label>
  23. <input type="text" name="shopNumber" class="form-control" id="" placeholder="服装销量">
  24. </div>
  25. <div class="form-group">
  26. <label for="">上传图片</label>
  27. <input type="file" name="file">
  28. </div>
  29. <button type="submit" class="btn btn-primary">提交</button>
  30. </form>
  31. </body>
  32. </html>

2.add.js

  1. const router = require("koa-router")();
  2. // 查询数据库
  3. router.get("/add",async ctx=>{
  4. await ctx.render("add")
  5. })
  6. module.exports = router;

3.doAdd.js

  1. const router = require("koa-router")();
  2. const path = require("path");
  3. const ShopMangeModel = require("../models/shopMange");
  4. // 查询数据库
  5. const fileUpload = require("../utils/upload");
  6. router.post("/doAdd",async ctx=>{
  7. console.log(ctx.request.files);
  8. var file=ctx.request.files.file;
  9. var uploadName = path.basename(file.path);
  10. var isUpload = Boolean(file.name.trim());
  11. // console.log(uploadName);
  12. // console.log(isUpload);
  13. /* 将本地图片放到服务器的static文件夹中 */
  14. if(isUpload){
  15. fileUpload(file.path,uploadName);
  16. var avatar = ctx.origin +"/"+uploadName;
  17. var {shopname,price,shopNumber} = ctx.request.body;
  18. console.log(ctx.request.body);
  19. var data = new ShopMangeModel({
  20. shopname,
  21. price: Number(price),
  22. shopNumber: Number(shopNumber),
  23. avatar
  24. })
  25. data.save(err => {
  26. if (err) {
  27. throw err
  28. };
  29. })
  30. }
  31. ctx.redirect("/")
  32. })
  33. module.exports = router;