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.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);
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'); }
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','增長輪播圖成功'); }
cnpm install silly-datetime --save cnpm install mz-modules --save
引入html
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){ // 一、獲取當前日期 20180920 var day=sd.format(new Date(), 'YYYYMMDD'); //二、建立圖片保存的路徑 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;