ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
学习目标 * [ ] 常用中间件的综合应用 * [ ] koa-router * [ ] koa-views(nunjucks模版引擎) * [ ] koa-multer * [ ] koa-compose ![](https://box.kancloud.cn/f83c9a3c552da93bacf1f000c0f72939_257x378.png) # 视图模版 视图文件:`/views/multer.html` ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>图片上传</title> </head> <body> <h2>{{title}}</h2> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="确定" /> </form> </body> </html> ``` # 主应用代码 应用代码` /app-multer.js` ```javascript const Koa = require('koa') const multer = require('koa-multer') const Router = require('koa-router') const views = require('koa-views') const compose = require('koa-compose'); const path = require('path') const app = new Koa() app.use(views(path.join(__dirname, 'views'), { extension: 'html', map: { html: 'nunjucks' } //需要安装nunjucks包 })) const router = new Router() router.get('/', async (ctx, next) => { await ctx.render('multer', { title: 'Hello koa2' }) }) //文件上传 //配置 const storage = multer.diskStorage({ //文件保存路径 destination: function (req, file, cb) { cb(null, 'public/uploads/') }, //修改文件名称 filename: function (req, file, cb) { var fileFormat = (file.originalname).split("."); //以点分割成数组,数组的最后一项就是后缀名 cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]); } }) //加载配置 const upload = multer({ storage: storage }); //路由 router.post('/upload', upload.single('file'), async (ctx, next) => { ctx.body = { filename: ctx.req.file.filename//返回文件名 } }) //组合多个中间件,中间件执行区分顺序 const all = compose([router.routes(), router.allowedMethods()]); app.use(all); app.listen(3000, () => { console.log('server is running at http://localhost:3000') }); ``` 启动脚本 ``` $node app-multer.js ```