m1/add.js
const router = require("koa-router")();
// 查询数据库
router.get("/m1/add",async ctx=>{
await ctx.render('add')
})
module.exports = router;
add.html
<form action="/m1/doAdd" method="POST" role="form" enctype="multipart/form-data">
<legend>添加数据</legend>
<div class="form-group">
<label for="">姓名</label>
<input type="text" class="form-control" name="name" placeholder="Input field">
</div>
<div class="form-group">
<label for="">年龄</label>
<input type="text" class="form-control" name="age" placeholder="Input field">
</div>
<div class="form-group">
<label for="">点赞</label>
<input type="checkbox" name="like">
</div>
<div class="form-group">
<label for="">是否是好友</label>
<input type="checkbox" name="friend">
</div>
<div class="form-group">
<label for="">上传图片</label>
<input type="file" name="file">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
utils/upload.js 封装 文件上传模块
/*
localPath 上传图片所在的路径
uploadName 上传到服务器的图片名
*/
const fs = require('fs') // 使用这个模块可以实现文件的读和写
function fileUpload(localPath,uploadName){
// 创建可读流
const reader = fs.createReadStream(localPath);
// 获取上传文件扩展名
let filePath = process.cwd() + `/static/${uploadName}`;
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
}
module.exports=fileUpload
m1/doAdd.js
const router = require("koa-router")();
const path = require("path")
const fileUpload = require("../utils/upload");
const MembersModel = require("../models/Members")
router.post("/m1/doAdd",async ctx=>{
var file = ctx.request.files.file
var uploadName =path.basename(file.path)
/* 将本地图片放到服务器的static文件夹中 */
if(file.name.trim()){
fileUpload(file.path,uploadName)
var avatar = ctx.origin+"/"+uploadName
var {name,age,like,friend} = ctx.request.body
var data = new MembersModel({
name,
age: Number(age),
like: Boolean(like),
friend: Boolean(friend),
avatar
})
data.save(err => {
if (err) {
throw err
};
})
}
await ctx.redirect('/m1')
})
module.exports = router;