1、前置条件:
安装koa、koa-views、koa-multer、ejs、koa-router
cnpm i koa koa-views koa-multer ejs -S
cnpm i koa-router -S
2、准备模板文件 views/index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>图片上传</title>
<script src="http://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<%= title %>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="ok"/>
</form>
</body>
</html>
3、demos/multer.js
const Koa=require('koa')
const multer=require('koa-multer')
const Router=require('koa-router')
const views=require('koa-views')
const path=require('path')
const app=new Koa()
//加载模板引擎
app.use(views(path.join(__dirname,'../views'),{
extension:'ejs'
}))
const router=new Router()
router.get('/',async (ctx,next)=>{
let title = 'hello koa2'
await ctx.render('index', {
title
})
})
//文件上传
//配置
var 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]);
}
})
//加载配置
var upload = multer({ storage: storage });
//路由
router.post('/upload',upload.single('file'),async(ctx,next)=>{
console.log('abc')
ctx.body = {
filename: ctx.req.file.filename//返回文件名
}
})
app.use(router.routes(), router.allowedMethods())
app.listen(5555,()=>{
console.log('Server is running at port 5555...')
})
4、说明
上面代码中,文件的存放路径是 public/uploads,所以测试时要先建好该目录
启动:
node demos/multer.js
参考网址:https://blog.csdn.net/ziwoods/article/details/72822730