koa-body 配置文件上传// src/index.ts
KoaBody({
// 启用表单解析,可以支持文件上传
multipart: true,
formidable: {
// 文件上传路径
uploadDir: './uploads',
// 保持文件的扩展名
keepExtensions: true,
// 文件上传大小限制,默认5M
maxFieldsSize: 5 * 1024 * 1024,
// 保持文件的扩展名
onFileBegin: (name, file) => {
// 文件上传前的设置
// console.log(name, file);
},
},
})
文件上传接口 src/controller/common/view.tsimport { Context } from 'koa';
import type { Files, File as FileType } from 'formidable';
class IndexController {
……
async upload(ctx: Context) {
const files: Files | undefined = ctx.request.files;
if (files) {
const data: { url: string; name: string; size: number }[] = [];
for (const key in files) {
const file: FileType = files[key] as FileType;
data.push({
url: file.path,
name: file.name!,
size: file.size,
});
}
response.success(ctx, data, '上传成功');
} else {
response.error(ctx, '上传失败');
}
}
}
配置路由// src/controller/common/view.ts
import IndexController from '../controller/common/view';
router.post('/upload', IndexController.upload);
本文出自快速备案,转载时请注明出处及相应链接。