1 前端数据通过form表单提交。
tips:一定要加enctype=”multipart/form-data”
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
//用的bootstrap
<form action="" method="POST" role="form" enctype="multipart/form-data">
<legend>图片上传</legend>
<div class="form-group">
<label for="">label</label>
<input type="file" id="" name="file">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
2 后端导入
安装
yarn add koa-multer
模块化封装
const multer = require('koa-multer');//文件上传
// 配置文件上传
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, `${process.cwd()}/static/upLoad`)
},
filename: function (req, file, cb) {
let type = file.originalname.split('.')[1]
cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
}
})
//加载配置
var upload = multer({
storage: storage
});
module.exports = upload;
路由中使用
router.post("/m1/doAdd",upload.single('file'),async ctx=>{
// 这里数据要用ctx.req.body来获取
console.log(ctx.req.body);
// 保存文件到数据库
let {id,name,age,like} = ctx.req.body;
var imageUrl = ctx.req.file.filename;
var data = new MembersModel({name,age,like,state:false,imageUrl});
data.save(err=>{
if(err){throw err};
})
})