1 前端数据通过form表单提交。

tips:一定要加enctype=”multipart/form-data”
  1. <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
  2. //用的bootstrap
  3. <form action="" method="POST" role="form" enctype="multipart/form-data">
  4. <legend>图片上传</legend>
  5. <div class="form-group">
  6. <label for="">label</label>
  7. <input type="file" id="" name="file">
  8. </div>
  9. <button type="submit" class="btn btn-primary">Submit</button>
  10. </form>

2 后端导入

安装

  1. yarn add koa-multer

模块化封装

  1. const multer = require('koa-multer');//文件上传
  2. // 配置文件上传
  3. const storage = multer.diskStorage({
  4. destination: function (req, file, cb) {
  5. cb(null, `${process.cwd()}/static/upLoad`)
  6. },
  7. filename: function (req, file, cb) {
  8. let type = file.originalname.split('.')[1]
  9. cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
  10. }
  11. })
  12. //加载配置
  13. var upload = multer({
  14. storage: storage
  15. });
  16. module.exports = upload;

路由中使用

  1. router.post("/m1/doAdd",upload.single('file'),async ctx=>{
  2. // 这里数据要用ctx.req.body来获取
  3. console.log(ctx.req.body);
  4. // 保存文件到数据库
  5. let {id,name,age,like} = ctx.req.body;
  6. var imageUrl = ctx.req.file.filename;
  7. var data = new MembersModel({name,age,like,state:false,imageUrl});
  8. data.save(err=>{
  9. if(err){throw err};
  10. })
  11. })