目录
1. MVC
- mvc 即 model 、view、controller;mvc模式将model、view、controller分离;使用mvc分层是系统更加灵活,扩展性更强。让程序更加直观、复用性更强、可维护性更强。
- model 负责数据访问;
- view 负责视图呈现;
- controller负责消息处理;
2. 基于MVC的后端管理系统例子
完整代码: link.
3. 文件上传详解
3.1 文件上传采用的中间件—koa-body
- 在
app.js
中进行引入
const koaBody = require("koa-body");
app.use(koaBody({
multipart:true // 允许上传文件
}));
3.2 pug文件设置
- 设置格式以便能上传图片
views/admin/addNews.pug
enctype="multipart/form-data"
form.addInput(method='post', action='/admin/addData' enctype="multipart/form-data")
3.3 路由路径设置
- 在
router/adminRouter.js
中
const adminRouter = require("../controller/admin");
router.post("/addData", adminRouter.addData);
3.4 在控制层controller
编写逻辑
- 通过中间件
koa-body
使得ctx.request
可以获取前端传来的数据
const adminModel = require("../../service/admin");
module.exports = {
async addData(ctx) {
let res = await adminModel.addData(ctx.request);
console.log(res);
let info;
if (res.affectedRows > 0) {
info = {
info: "操作成功",
status: 1
}
} else {
info = {
info: "操作失败",
status: 0
}
}
ctx.body = info;
}
}
3.5 在model层进行文件上传数据库操作
service/admin/index.js
module.exports = {
async addData(request) {
let { title, type } = request.body;
// console.log(request.files.img)
if (request.files.img.size > 0) {
// 转存到指定文件夹;
if (!fs.existsSync("E:/practice/news/static/uploads")) {
fs.mkdirSync("E:/practice/news/static/uploads");
}
let tempPath = request.files.img.path;
fs.writeFileSync("E:/practice/news/static/uploads" + request.files.img.name, fs.readFileSync(tempPath));
let imgUrl = "/uploads/" + request.files.img.name
let newTime = new Date().getFullYear();
//数据添加到数据库;
let [rows] = await connection.promise().query("INSERT INTO news(title,imgUrl,`from`,newTime) VALUES (?,?,?,?)", [title, imgUrl, type, newTime]);
console.log(rows);
return rows;
}
}
}