前端
view
app/view/admin/focus/add.html
<form action="/admin/focus/doAdd?_csrf=<%= csrf %>" method="post" enctype="multipart/form-data">
<ul>
<li>名称: <input type="text" name="title" /></li>
<li>跳转地址: <input type="text" name="link" /></li>
<li>轮播图: <input type="file" name="focus_img" /></li>
<li>排序: <input type="text" name="sort" /></li>
<li>状态:
<input type="radio" name="status" checked value="1" id="a"/><label for="a">显示</label>
<input type="radio" name="status" checked value="0" id="b"/><label for="b">隐藏</label>
</li>
<li>
<br />
<button type="submit" class="btn btn-default">提交</button>
</li>
</ul>
</form>
后台
router.js
router.get('/admin/focus', controller.admin.focus.index);
router.get('/admin/focus/add', controller.admin.focus.add);
router.post('/admin/focus/doAdd', controller.admin.focus.doAdd);
model
app/model/focus.js
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
var d=new Date();
const FocusSchema = new Schema({
title: { type: String },
type: { type: Number },
focus_img: { type: String },
link:{type:String},
sort:{ type: Number },
status:{
type:Number,
default:1
},
add_time:{
type:Number,
default:d.getTime()
}
});
return mongoose.model('Focus', FocusSchema,'focus');
}
controller
app/controller/admin/focus.js
async doAdd() {
let parts = this.ctx.multipart({autoFields:true});
let files = {};
let stream;
while((stream = await parts()) != null){
if(!stream.filename){
break;
}
let fieldname = stream.fieldname; //file表单的名字
//上传图片的目录
let dir = await this.service.tools.getUploadFile(stream.filename);
let target = dir.uploadDir;
let writeStream = fs.createWriteStream(target);
await pump(stream,writeStream);
files = Object.assign(files,{
[fieldname]:dir.saveDir
})
}
let focus = new this.ctx.model.Focus(Object.assign(files,parts.field));
var result = await focus.save();
await this.success('/admin/focus','增加轮播图成功');
}
service
安装依赖
cnpm install silly-datetime --save
cnpm install mz-modules --save
引入
const sd = require('silly-datetime');
const mkdirp = require('mz-modules/mkdirp');
app/service/tools.js
'use strict';
const sd = require('silly-datetime');
const path = require('path');
const mkdirp = require('mz-modules/mkdirp');
const Service = require('egg').Service;
class ToolsService extends Service {
async getUploadFile(filename){
// 1、获取当前日期 20180920
var day=sd.format(new Date(), 'YYYYMMDD');
//2、创建图片保存的路径
var dir=path.join(this.config.uploadDir,day);
await mkdirp(dir);
var d=new Date();
d=d.getTime(); /*毫秒数*/
//返回图片保存的路径
var uploadDir=path.join(dir,d+path.extname(filename));
// app\public\admin\upload\20180914\1536895331444.png
return {
uploadDir:uploadDir,
saveDir:uploadDir.slice(3).replace(/\\/g,'/')
}
}
}
module.exports = ToolsService;