使用 Koa2 创建文件上传接口并使用 Postman 测试

本文介绍如何使用 Koa2 创建一个简单的文件上传接口,然后介绍使用 Postman 对其进行测试的详细步骤。

准备工作

  • 已安装 Node.js
  • 具有 JavaScript 和 Node.js 的基本知识
  • 已安装 Postman 用于测试

第 1 步:建立项目

创建一个新目录,并进入该目录:

bash 复制代码
mkdir koa-file-upload
cd koa-file-upload

初始化一个新的 Node.js 项目:

bash 复制代码
npm init -y

安装 koakoa-body(用于解析请求体和文件的中间件):

bash 复制代码
npm install koa koa-router koa-body --save

第 2 步:创建 Koa 服务器

创建一个名为 app.js 的文件:

bash 复制代码
touch app.js

app.js 中,设置一个基本的 Koa 服务器:

javascript 复制代码
const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');

const app = new Koa();
const router = new Router();

app.use(koaBody({ multipart: true }));

// 在这里定义路由

app.use(router.routes()).use(router.allowedMethods());

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`服务器正在运行于 http://localhost:${PORT}`);
});

第 3 步:创建文件上传端点

app.js 中添加以下代码,创建一个文件上传端点:

javascript 复制代码
router.post('/upload', async (ctx) => {
    const file = ctx.request.files.file; // 从请求中获取文件
    const reader = fs.createReadStream(file.filepath); // 创建一个读取文件的流
    const stream = fs.createWriteStream(path.join(__dirname, 'uploads', file.originalFilename)); // 创建一个写入文件的流
    reader.pipe(stream); // 将读取流导向写入流
    console.log('正在上传 %s -> %s', file.originalFilename, stream.path);

    ctx.body = '文件成功上传';
});

确保在项目根目录中创建一个 uploads 目录来存储上传的文件:

bash 复制代码
mkdir uploads

第 4 步:启动服务器

运行 Koa 服务器:

bash 复制代码
node app.js

第 5 步:使用 Postman 进行测试

打开 Postman,按照以下步骤测试文件上传 API:

  1. 点击 'New' 按钮并选择 'Request' 来创建一个新请求。
  2. 将请求方法设置为 'POST'。
  3. 输入 URL http://localhost:3000/upload
  4. 转到 'Body' 选项卡,选择 'form-data'。
  5. 在 'Key' 下,将类型改为 'File'。
  6. 输入 'file' 作为键,并从您的系统中选择要上传的文件。
  7. 点击 'Send' 按钮执行请求。

如果此次数据交换成功,则客户端收到 '文件成功上传' 的响应,文件现在应该在后端项目的 uploads 目录中。

额外提示

  • 在生产代码中始终处理错误情况。
  • 为了安全起见,实施文件类型和大小验证。
  • 在实际应用中确保有适当的流事件错误处理。

基于此基本文件上传服务,并已经使用 Postman 进行了测试。您可以通过添加更多功能,如文件类型检查、存储服务集成和更健全的错误处理,来扩展这个服务。


English version

Creating a File Upload API with Koa2 and Testing with Postman

This guide will walk you through setting up a simple file upload API using Koa2 and testing it using Postman.

Prerequisites

  • Node.js installed
  • Basic knowledge of JavaScript and Node.js
  • Postman installed for testing

Step 1: Set Up Your Project

First, create a new directory for your project and navigate into it:

bash 复制代码
mkdir koa-file-upload
cd koa-file-upload

Initialize a new Node.js project:

bash 复制代码
npm init -y

Install koa and koa-body (middleware to parse the body and files):

bash 复制代码
npm install koa koa-router koa-body --save

Step 2: Create the Koa Server

Create a file named app.js:

bash 复制代码
touch app.js

Inside app.js, set up a basic Koa server:

javascript 复制代码
const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');

const app = new Koa();
const router = new Router();

app.use(koaBody({ multipart: true }));

// Define routes here

app.use(router.routes()).use(router.allowedMethods());

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 3: Create File Upload Endpoint

Add the following code to app.js to create a file upload endpoint:

javascript 复制代码
router.post('/upload', async (ctx) => {
  const file = ctx.request.files.file; // Get the file from the request
  const reader = fs.createReadStream(file.filepath); // Create a stream to read the file
  const stream = fs.createWriteStream(path.join(__dirname, 'uploads', file.originalFilename)); // Create a stream to write the file
  reader.pipe(stream); // Pipe the read stream to the write stream
  console.log('uploading %s -> %s', file.originalFilename, stream.path);

  ctx.body = 'File uploaded successfully';
});

Make sure to create an uploads directory in the root of your project to store the uploaded files:

bash 复制代码
mkdir uploads

Step 4: Start the Server

Run your Koa server by executing:

bash 复制代码
node app.js

Step 5: Test with Postman

Open Postman and follow these steps to test your file upload API:

  1. Create a new request by clicking the 'New' button and selecting 'Request'.
  2. Set the request method to 'POST'.
  3. Enter the URL `http://localhost:

3000/upload`. 4. Go to the 'Body' tab and select 'form-data'. 5. Under 'Key', change the type to 'File'. 6. Enter 'file' as the key and select the file you want to upload from your system. 7. Click the 'Send' button to execute the request.

You should receive a response that says 'File uploaded successfully', and the file should now be in the uploads directory of your project.

Additional Tips

  • Always handle error cases in your production code.
  • Implement file type and size validation for security purposes.
  • Make sure to have proper error handling for stream events in real-world applications.

Now, you have a basic file upload service running with Koa2 and have tested it with Postman. You can expand upon this by adding more features like file type checks, storage service integration, and more robust error handling.

相关推荐
无责任此方_修行中3 小时前
如何利用 pnpm 的安全控制功能防御 npm 供应链攻击
javascript·npm·node.js
允许部分打工人先富起来3 小时前
在node项目中执行python脚本
前端·python·node.js
None32121 小时前
【NestJs】基于Redlock装饰器分布式锁设计与实现
后端·node.js
Gogo11211 天前
构建高性能 Node.js 集中式日志体系 (下篇):Pino + PM2 + OpenSearch 代码落地实战
node.js
小岛前端1 天前
Node.js 宣布重大调整,运行十年的规则要改了!
前端·node.js
前端付豪1 天前
Nest 项目小实践之前端注册登陆
前端·node.js·nestjs
codingWhat2 天前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
ServBay2 天前
Node.js、Bun 与 Deno,2026 年后端运行时选择指南
node.js·deno·bun
码路飞2 天前
Node.js 中间层我维护了两年,这周终于摊牌了——成本账单算完我人傻了
node.js
None3213 天前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js