m1/add.js

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

add.html

  1. <form action="/m1/doAdd" method="POST" role="form" enctype="multipart/form-data">
  2. <legend>添加数据</legend>
  3. <div class="form-group">
  4. <label for="">姓名</label>
  5. <input type="text" class="form-control" name="name" placeholder="Input field">
  6. </div>
  7. <div class="form-group">
  8. <label for="">年龄</label>
  9. <input type="text" class="form-control" name="age" placeholder="Input field">
  10. </div>
  11. <div class="form-group">
  12. <label for="">点赞</label>
  13. <input type="checkbox" name="like">
  14. </div>
  15. <div class="form-group">
  16. <label for="">是否是好友</label>
  17. <input type="checkbox" name="friend">
  18. </div>
  19. <div class="form-group">
  20. <label for="">上传图片</label>
  21. <input type="file" name="file">
  22. </div>
  23. <button type="submit" class="btn btn-primary">添加</button>
  24. </form>

utils/upload.js 封装 文件上传模块

  1. /*
  2. localPath 上传图片所在的路径
  3. uploadName 上传到服务器的图片名
  4. */
  5. const fs = require('fs') // 使用这个模块可以实现文件的读和写
  6. function fileUpload(localPath,uploadName){
  7. // 创建可读流
  8. const reader = fs.createReadStream(localPath);
  9. // 获取上传文件扩展名
  10. let filePath = process.cwd() + `/static/${uploadName}`;
  11. // 创建可写流
  12. const upStream = fs.createWriteStream(filePath);
  13. // 可读流通过管道写入可写流
  14. reader.pipe(upStream);
  15. }
  16. module.exports=fileUpload

m1/doAdd.js

  1. const router = require("koa-router")();
  2. const path = require("path")
  3. const fileUpload = require("../utils/upload");
  4. const MembersModel = require("../models/Members")
  5. router.post("/m1/doAdd",async ctx=>{
  6. var file = ctx.request.files.file
  7. var uploadName =path.basename(file.path)
  8. /* 将本地图片放到服务器的static文件夹中 */
  9. if(file.name.trim()){
  10. fileUpload(file.path,uploadName)
  11. var avatar = ctx.origin+"/"+uploadName
  12. var {name,age,like,friend} = ctx.request.body
  13. var data = new MembersModel({
  14. name,
  15. age: Number(age),
  16. like: Boolean(like),
  17. friend: Boolean(friend),
  18. avatar
  19. })
  20. data.save(err => {
  21. if (err) {
  22. throw err
  23. };
  24. })
  25. }
  26. await ctx.redirect('/m1')
  27. })
  28. module.exports = router;