在 Koa 中实现上传文件的过程大致如下:

  1. 安装 koa-body 和 koa-router 模块
npm install koa-body koa-router
  1. 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();
  1. 配置 koa-body 中间件,使得 Koa 能够识别上传的文件
app.use(koaBody({
  multipart: true, // 支持文件上传
  formidable: {
    maxFieldsSize: 2 * 1024 * 1024, // 最大文件大小为 2MB
    multipart: true // 支持多文件上传
  }
}));
  1. 设置路由,处理文件上传请求
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
    }
  };
});
  1. 启动 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'));
koa 实现上传文件

原文地址: https://www.cveoy.top/t/topic/ba8R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录