安装
npm i @koa/multer
注
安装 npm i @koa/multer 警告如下:
npm warn deprecated @babel/plugin-proposal-export-namespace-from@7.18.9:
This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained.
Please use @babel/plugin-transform-export-namespace-from instead.
这个警告说明使用的插件(@babel/plugin-proposal-export-namespace-from)已过时,
该语法已合并到了 ES 标准中, 因此不再需要此插件进行转换
import Koa from 'koa'
import Router from '@koa/router'
import BodyParser from '@koa/bodyparser'
import Cors from '@koa/cors'
import Multer from '@koa/multer'
import path from 'path'
const hostname = "127.0.0.1"
const port = 8008
const app = new Koa()
const router = new Router() //实例化一个 Router 对象
app.use(BodyParser()) //使用 @koa/bodyparser 中间件来解析 post 请求
app.use(Cors()) //允许跨域请求
//配置磁盘存储引擎
const storage = Multer.diskStorage({
destination: (request, file, callbackFunc) => { //指定文件保存路径
callbackFunc(null, './upload')
},
filename: (request, file, callbackFunc) => { //设置文件名
callbackFunc(null, Date.now() + path.extname(file.originalname))
},
})
const multer = Multer({ //实例化一个 Multer 对象
storage, //磁盘存储引擎
limits: { //限制条件
fileSize: 2 * 1024 * 1024, // 限制文件大小为2MB
},
fileFilter: (request, file, callbackFunc) => { //文件过滤器
let allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
if (allowedTypes.includes(file.mimetype)) {
callbackFunc(null, true)
} else {
callbackFunc(new Error('不支持的文件类型'), false)
}
}
})
//上传 http://127.0.0.1:8008/upload
router.post('/upload', multer.single('file'), async ctx => {
const file = ctx.request.file // 获取上传的文件信息
if (file) {
console.log(file)
ctx.body = "文件上传成功"
}
})
app.use(async (ctx, next) => { //错误处理中间件
try {
await next()
} catch (err) {
//console.log('err:', err)
ctx.status = 500
ctx.body = 'err: ' + err.message
}
})
app.use(router.routes()) //路由处理中间件
app.listen(port, hostname, () => {
console.log(`服务器已启动: http://${hostname}:${port}`)
})