1-1 加载页面
在controller 文件夹 新建 form.js
'use strict';
const Controller = require('egg').Controller;
class FormController extends Controller {
async index() {
const { ctx } = this;
await ctx.render('form')
}
}
module.exports = FormController;
在view 文件夹 新建 form.html
<div class="container">
<form action="/doForm" method="POST" role="form" enctype="multipart/form-data">
<legend>添加小组成员</legend>
<div class="form-group">
<label for="">姓名</label>
<input type="text" class="form-control" name="username" placeholder="请输入名字">
</div>
<div class="form-group">
<label for="">年龄</label>
<input type="text" class="form-control" name="age" placeholder="请输入年龄">
</div>
<div class="form-group">
<label for="">性别</label>
<input type="text" class="form-control" name="sex" placeholder="请输入年龄">
</div>
<div class="form-group">
<label for="">上传图形</label>
<input type="file" class="form-control" name="logo" placeholder="Input field">
</div>
<button type="submit" class="btn btn-primary">添加数据</button>
</form>
</div>
对应路由
router.get('/form', controller.form.index);
1-2 对应提交页面
配置
config/config.default.js
config.multipart = {
mode: 'file',
};
在controller 文件夹 新建 doForm.js
路由
router.post('/doForm', controller.doForm.index);
#doForm.js
'use strict';
const Controller = require('egg').Controller;
//上传文件
const fs = require('mz/fs');
const path = require("path")
class DoFormController extends Controller {
async index() {
const { ctx } = this;
// console.log(ctx.request.body);
// console.log(ctx.request.files[0].filepath);
//拿到提交数据
var { username, age, sex } = ctx.request.body;
age = Number(age)
// console.log(username);
//上传的图片路径
var filename = ctx.request.files[0].filepath;
// console.log(filename);
var reader = fs.createReadStream(filename);
//静态资源 写入路径
var uploadFile = `${process.cwd()}/app/public/${path.basename(filename)}`;
// console.log(uploadFile);
var write = fs.createWriteStream(uploadFile);
reader.pipe(write);
//图片完整路径
//主机ip+存放路径public+文件后缀名
var logo = ctx.origin + "/public/" + path.basename(filename);
// console.log(logo);
//连接数据库
var db = this.app.mongodb;
const collection = await db.collection("member");
// console.log(collection);
//添加数据 与 数据库数据 比较 是否一样
var res = await db.collection("member").find({ username }).toArray();
if (res.length) {
ctx.body = "<script>alert('已添加过该成员');location.href='/form'</script>"
} else {
//数据上传到数据库
await collection.insertOne({ username, age, sex, logo })
await ctx.redirect("/home")
}
}
}
module.exports = DoFormController;