# @eggjs/multipart 中文文档

规范地址：https://npmcn.com/package/%40eggjs/multipart/

版本：5\.1\.0
npm 元数据更新时间：2026-10-07T08:19:54.451Z
中文译文更新时间：2026-11-13T10:00:27.042Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40eggjs/multipart
原文对照：https://npmcn.com/package/%40eggjs/multipart/?lang=original
项目主页：https://github.com/eggjs/egg/tree/next/plugins/multipart#readme
源码仓库：https://github.com/eggjs/egg

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：38.3 kB，23 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>= 22\.18\.0
- 运行依赖：4 个
- peer 依赖：egg 4\.2\.0
- 首次发布：2025-02-03T14:49:23.619Z
- 最新版本发布：2026-10-07T08:19:54.060Z
- 近 30 天下载量：4746（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：52（近 12 个月 33 个）

## 中文简介

彩蛋多块插件

## 安装

```sh
npm install @eggjs/multipart
```

也可以使用：`pnpm add @eggjs/multipart`、`yarn add @eggjs/multipart`、`bun add @eggjs/multipart`

## README

# @eggjs/多块

[![NPM version](https://img.shields.io/npm/v/@eggjs/multipart.svg?style=flat-square)](https://npmjs.org/package/@eggjs/multipart) [![Known Vulnerabilities](https://snyk.io/test/npm/@eggjs/multipart/badge.svg?style=flat-square)](https://snyk.io/test/npm/@eggjs/multipart) [![npm download](https://img.shields.io/npm/dm/@eggjs/multipart.svg?style=flat-square)](https://npmjs.org/package/@eggjs/multipart) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com/) ![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/eggjs/multipart)

使用 [公交车](https://github.com/cojs/busboy) 通过流媒体上传文件 处理它而不保存到磁盘(使用 `stream` 模式).

刚刚使用 `ctx.multipart()` ,然后传递到图像处理模块,例如 `gm` 或上传到云存储等 `oss`。 。 。 .

## 文件扩展名的白名单

对于安全性,如果上传的文件扩展名不在白名单中,则会以 `400 Bad request`。 。 。 .

默认白名单 :

```js
const whitelist = [
  // images
  '.jpg',
  '.jpeg', // image/jpeg
  '.png', // image/png, image/x-png
  '.gif', // image/gif
  '.bmp', // image/bmp
  '.wbmp', // image/vnd.wap.wbmp
  '.webp',
  '.tif',
  '.psd',
  // text
  '.svg',
  '.js',
  '.jsx',
  '.json',
  '.css',
  '.less',
  '.html',
  '.htm',
  '.xml',
  // tar
  '.zip',
  '.gz',
  '.tgz',
  '.gzip',
  // video
  '.mp3',
  '.mp4',
  '.avi',
];
```

### 文件大小

默认文件大小 `10mb`。如果上传一个大文件,请指定此配置.

```js
// config/config.default.js
exports.multipart = {
  fileSize: '50mb',
};
```

### 自定义配置

开发者可以自定义额外的文件扩展名 :

```js
// config/config.default.js
exports.multipart = {
  // will append to whilelist
  fileExtensions: ['.foo', '.apk'],
};
```

还可以 **覆盖** 内置白名单, 如只允许 png :

```js
// config/config.default.js
exports.multipart = {
  whitelist: ['.png'],
};
```

或按函数:

```js
exports.multipart = {
  whitelist: (filename) => ['.png'].includes(path.extname(filename) || ''),
};
```

**注:如果定义 `whitelist`,则 `fileExtensions` 将被忽略.**

## 实例

更多例子如下:

-   [处理多段请求 `stream` 模式](https://github.com/eggjs/examples/tree/master/multipart)
-   [处理多段请求 `file` 模式](https://github.com/eggjs/examples/tree/master/multipart-file-mode)

## `file` 模式: 简单的方式

如果你不知道的话 [节点.js流](https://nodejs.org/dist/latest-v18.x/docs/api/stream.html) 劳动, 也许你应该用 `file` 模式开始.

用途与 [车体处理器](https://eggjs.org/en/basics/controller.html#body)。 。 。 .

-   `ctx.request.body`: 获取所有多块字段和值, 但 `file`。 。 。 .
-   `ctx.request.files`: 包含全部 `file` 从多段请求,它是一个矩阵对象.

**警告:使用后, 您应该删除临时上传文件**, (中文(简体) ), 页:1 `async ctx.cleanupRequestFiles()` 方法将非常有用.

### 启用 `file` 配置模式

你需要设定 `config.multipart.mode = 'file'` 启用 `file` 模式 :

```js
// config/config.default.js
exports.multipart = {
  mode: 'file',
};
```

之后 `file` 模式启用, egg 将删除旧的临时文件( 不包括今天的文件) `04:30 AM` 每天默认.

```js
config.multipart = {
  mode: 'file',
  tmpdir: path.join(os.tmpdir(), 'egg-multipart-tmp', appInfo.name),
  cleanSchedule: {
    // run tmpdir clean job on every day 04:30 am
    // cron style see https://github.com/eggjs/egg-schedule#cron-style-scheduling
    cron: '0 30 4 * * *',
    disable: false,
  },
};
```

默认将使用最后一个同名字段, 如果需要所有字段值, 请设置 `allowArrayField` 在配置中.

```js
// config/config.default.js
exports.multipart = {
  mode: 'file',
  allowArrayField: true,
};
```

### 上传一个文件

```html
<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  title: <input name="title" /> file: <input name="file" type="file" />
  <button type="submit">Upload</button>
</form>
```

自动控制器 `POST /upload`数字 :

```js
// app/controller/upload.js
const Controller = require('egg').Controller;
const fs = require('mz/fs');

module.exports = class extends Controller {
  async upload() {
    const { ctx } = this;
    const file = ctx.request.files[0];
    const name = 'egg-multipart-test/' + path.basename(file.filename);
    let result;
    try {
      // process file or upload to cloud storage
      result = await ctx.oss.put(name, file.filepath);
    } finally {
      // remove tmp files and don't block the request's response
      // cleanupRequestFiles won't throw error even remove file io error happen
      ctx.cleanupRequestFiles();
      // remove tmp files before send response
      // await ctx.cleanupRequestFiles();
    }

    ctx.body = {
      url: result.url,
      // get all field values
      requestBody: ctx.request.body,
    };
  }
};
```

### 上传多文件

```html
<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  title: <input name="title" /> file1: <input name="file1" type="file" /> file2: <input name="file2" type="file" />
  <button type="submit">Upload</button>
</form>
```

自动控制器 `POST /upload`数字 :

```js
// app/controller/upload.js
const Controller = require('egg').Controller;
const fs = require('mz/fs');

module.exports = class extends Controller {
  async upload() {
    const { ctx } = this;
    console.log(ctx.request.body);
    console.log('got %d files', ctx.request.files.length);
    for (const file of ctx.request.files) {
      console.log('field: ' + file.fieldname);
      console.log('filename: ' + file.filename);
      console.log('encoding: ' + file.encoding);
      console.log('mime: ' + file.mime);
      console.log('tmp filepath: ' + file.filepath);
      let result;
      try {
        // process file or upload to cloud storage
        result = await ctx.oss.put('egg-multipart-test/' + file.filename, file.filepath);
      } finally {
        // remove tmp files and don't block the request's response
        // cleanupRequestFiles won't throw error even remove file io error happen
        ctx.cleanupRequestFiles([file]);
      }
      console.log(result);
    }
  }
};
```

## `stream` 模式: 困难方式

如果你熟知节点 Js Stream的作品 你应该用 `stream` 模式.

### 使用方式 `for await...of`

```html
<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  title: <input name="title" /> file1: <input name="file1" type="file" /> file2: <input name="file2" type="file" />
  <button type="submit">Upload</button>
</form>
```

自动控制器 `POST /upload`数字 :

```js
// app/controller/upload.js
const { Controller } = require('egg');
const fs = require('fs');
const stream = require('stream');
const util = require('util');
const { randomUUID } = require('crypto');
const pipeline = util.promisify(stream.pipeline);

module.exports = class UploadController extends Controller {
  async upload() {
    const parts = this.ctx.multipart();
    const fields = {};
    const files = {};

    for await (const part of parts) {
      if (Array.isArray(part)) {
        // fields
        console.log('field: ' + part[0]);
        console.log('value: ' + part[1]);
      } else {
        // otherwise, it's a stream
        const { filename, fieldname, encoding, mime } = part;

        console.log('field: ' + fieldname);
        console.log('filename: ' + filename);
        console.log('encoding: ' + encoding);
        console.log('mime: ' + mime);

        // how to handler?
        // 1. save to tmpdir with pipeline
        // 2. or send to oss
        // 3. or just consume it with another for await

        // WARNING: You should almost never use the origin filename as it could contain malicious input.
        const targetPath = path.join(os.tmpdir(), randomUUID() + path.extname(filename));
        await pipeline(part, createWriteStream(targetPath)); // use `pipeline` not `pipe`
      }
    }

    this.ctx.body = 'ok';
  }
};
```

### 上传一个文件( DEPRECATED)

您可以通过上传流 `ctx.getFileStream*()`。 。 。 .

```html
<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  title: <input name="title" /> file: <input name="file" type="file" />
  <button type="submit">Upload</button>
</form>
```

处理器控制器 `POST /upload`数字 :

```js
// app/controller/upload.js
const path = require('node:path');
const { sendToWormhole } = require('stream-wormhole');
const { Controller } = require('egg');

module.exports = class extends Controller {
  async upload() {
    const { ctx } = this;
    // file not exists will response 400 error
    const stream = await ctx.getFileStream();
    const name = 'egg-multipart-test/' + path.basename(stream.filename);
    // process file or upload to cloud storage
    const result = await ctx.oss.put(name, stream);

    ctx.body = {
      url: result.url,
      // process form fields by `stream.fields`
      fields: stream.fields,
    };
  }

  async uploadNotRequiredFile() {
    const { ctx } = this;
    // file not required
    const stream = await ctx.getFileStream({ requireFile: false });
    let result;
    if (stream.filename) {
      const name = 'egg-multipart-test/' + path.basename(stream.filename);
      // process file or upload to cloud storage
      const result = await ctx.oss.put(name, stream);
    } else {
      // must consume the empty stream
      await sendToWormhole(stream);
    }

    ctx.body = {
      url: result && result.url,
      // process form fields by `stream.fields`
      fields: stream.fields,
    };
  }
};
```

### 上传多文件( DEPRECATED)

```html
<form method="POST" action="/upload?_csrf={{ ctx.csrf | safe }}" enctype="multipart/form-data">
  title: <input name="title" /> file1: <input name="file1" type="file" /> file2: <input name="file2" type="file" />
  <button type="submit">Upload</button>
</form>
```

自动控制器 `POST /upload`数字 :

```js
// app/controller/upload.js
const Controller = require('egg').Controller;

module.exports = class extends Controller {
  async upload() {
    const { ctx } = this;
    const parts = ctx.multipart();
    let part;
    while ((part = await parts()) != null) {
      if (part.length) {
        // arrays are busboy fields
        console.log('field: ' + part[0]);
        console.log('value: ' + part[1]);
        console.log('valueTruncated: ' + part[2]);
        console.log('fieldnameTruncated: ' + part[3]);
      } else {
        if (!part.filename) {
          // user click `upload` before choose a file,
          // `part` will be file stream, but `part.filename` is empty
          // must handler this, such as log error.
          continue;
        }
        // otherwise, it's a stream
        console.log('field: ' + part.fieldname);
        console.log('filename: ' + part.filename);
        console.log('encoding: ' + part.encoding);
        console.log('mime: ' + part.mime);
        const result = await ctx.oss.put('egg-multipart-test/' + part.filename, part);
        console.log(result);
      }
    }
    console.log('and we are done parsing the form!');
  }
};
```

### 支助 `file` 财务报告和审定财务报表 `stream` 模式在同一时间

如果默认 `mode` 实值 `stream`,使用 `fileModeMatch` 选项以匹配请求 urls 切换到 `file` 模式.

```js
config.multipart = {
  mode: 'stream',
  // let POST /upload_file request use the file mode, other requests use the stream mode.
  fileModeMatch: /^\/upload_file$/,
  // or glob
  // fileModeMatch: '/upload_file',
};
```

注意点: `fileModeMatch` 选项 `stream` 模式.

## 许可证

[麻省理工学院](https://npmcn.com/package/%40eggjs/multipart/LICENSE)

## 贡献者

[![Contributors](https://contrib.rocks/image?repo=eggjs/egg)](https://github.com/eggjs/egg/graphs/contributors)

制造的 [贡献者-img](https://contrib.rocks/)。 。 。 .

## 常见问题

### @eggjs/multipart 是什么？

彩蛋多块插件

### 如何安装 @eggjs/multipart？

在项目目录运行 npm install @eggjs/multipart，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：egg（4\.2\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @eggjs/multipart 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @eggjs/multipart 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @eggjs/multipart 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 22\.18\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @eggjs/multipart 可以商用吗？

@eggjs/multipart 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @eggjs/multipart 的下载量有多少？

根据 npm 官方下载统计，@eggjs/multipart 在 2026/10/13 – 2026/11/11 这 30 天内被下载 4,746 次，日均约 158 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @eggjs/multipart 还在维护吗？

最新版本 5\.1\.0 发布于 2026/10/07（1 个月前）；至今共发布 52 个版本，其中过去 12 个月发布了 33 个；首次发布于 2025/02/03。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

