Koa 文件上传教程:使用 koa-body 实现文件上传功能
Koa 文件上传教程:使用 koa-body 实现文件上传功能
本教程将带您一步步了解如何在 Koa 框架中使用 koa-body 模块实现文件上传功能,并提供完整代码示例。
1. 安装依赖
首先,我们需要安装 koa-body 和 koa-router 模块:
npm install koa-body koa-router
2. 引入模块
在 app.js 中引入 koa-body 和 koa-router 模块:
const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');
const app = new Koa();
const router = new Router();
3. 配置 koa-body 中间件
配置 koa-body 中间件,使得 Koa 能够识别上传的文件:
app.use(koaBody({
multipart: true, // 支持文件上传
formidable: {
maxFieldsSize: 2 * 1024 * 1024, // 最大文件大小为 2MB
multipart: true // 支持多文件上传
}
}));
4. 设置路由
设置路由,处理文件上传请求:
router.post('/upload', async (ctx, next) => {
const file = ctx.request.files.file; // 获取上传的文件
const reader = fs.createReadStream(file.path); // 创建可读流
const ext = file.name.split('.').pop(); // 获取文件后缀名
const filename = `${uuidv4()}.${ext}`; // 生成唯一文件名
const filePath = path.join(__dirname, 'public/uploads', filename); // 上传文件的路径
const upStream = fs.createWriteStream(filePath); // 创建可写流
reader.pipe(upStream); // 将可读流写入可写流
ctx.body = { // 返回上传成功的信息
status: 'success',
message: '文件上传成功',
data: {
url: `http://localhost:3000/uploads/${filename}`,
name: file.name,
type: file.type,
size: file.size
}
};
});
5. 启动 Koa 应用
最后,启动 Koa 应用:
app.use(router.routes());
app.listen(3000, () => console.log('Server started on port 3000'));
完整代码
const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const app = new Koa();
const router = new Router();
app.use(koaBody({
multipart: true,
formidable: {
maxFieldsSize: 2 * 1024 * 1024,
multipart: true
}
}));
router.post('/upload', async (ctx, next) => {
const file = ctx.request.files.file;
const reader = fs.createReadStream(file.path);
const ext = file.name.split('.').pop();
const filename = `${uuidv4()}.${ext}`;
const filePath = path.join(__dirname, 'public/uploads', filename);
const upStream = fs.createWriteStream(filePath);
reader.pipe(upStream);
ctx.body = {
status: 'success',
message: '文件上传成功',
data: {
url: `http://localhost:3000/uploads/${filename}`,
name: file.name,
type: file.type,
size: file.size
}
};
});
app.use(router.routes());
app.listen(3000, () => console.log('Server started on port 3000'));
注意:
- 请确保
public/uploads目录存在,并具有写入权限。 - 在实际项目中,您可能需要根据需要调整
maxFieldsSize和其他配置选项。 - 本教程仅提供基本的文件上传功能,您可能需要根据实际需求添加其他功能,例如文件类型验证、文件大小限制等。
原文地址: https://www.cveoy.top/t/topic/mBm7 著作权归作者所有。请勿转载和采集!