首页
/ Formidable 项目技术文档

Formidable 项目技术文档

2024-12-20 02:14:43作者:尤辰城Agatha

1. 安装指南

环境要求

  • Node.js 版本 >= 10.13

安装步骤

  1. 使用 npmyarn 安装 formidable 模块。
  2. 根据需要选择安装 v2v3 版本。
# 安装 v2 版本
npm install formidable@v2

# 安装 v3 版本
npm install formidable@v3

2. 项目的使用说明

概述

formidable 是一个用于解析表单数据的 Node.js 模块,特别是文件上传。它具有以下特点:

  • 快速的多部分解析器(~900-2500 mb/sec)
  • 自动将文件上传写入磁盘(可选)
  • 插件 API,允许自定义解析器和插件
  • 低内存占用
  • 优雅的错误处理
  • 高测试覆盖率

使用示例

以下是使用 formidable 模块的几个示例:

使用 Node.js http 模块

import http from 'node:http';
import formidable, {errors as formidableErrors} from 'formidable';

const server = http.createServer(async (req, res) => {
  if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({});
    let fields;
    let files;
    try {
        [fields, files] = await form.parse(req);
    } catch (err) {
        if (err.code === formidableErrors.maxFieldsExceeded) {
            // 处理特定错误
        }
        console.error(err);
        res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
        res.end(String(err));
        return;
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ fields, files }, null, 2));
    return;
  }

  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end(`
    <h2>With Node.js <code>"http"</code> module</h2>
    <form action="/api/upload" enctype="multipart/form-data" method="post">
      <div>Text field title: <input type="text" name="title" /></div>
      <div>File: <input type="file" name="multipleFiles" multiple="multiple" /></div>
      <input type="submit" value="Upload" />
    </form>
  `);
});

server.listen(8080, () => {
  console.log('Server listening on http://localhost:8080/ ...');
});

使用 Express.js

import express from 'express';
import formidable from 'formidable';

const app = express();

app.get('/', (req, res) => {
  res.send(`
    <h2>With <code>"express"</code> npm package</h2>
    <form action="/api/upload" enctype="multipart/form-data" method="post">
      <div>Text field title: <input type="text" name="title" /></div>
      <div>File: <input type="file" name="someExpressFiles" multiple="multiple" /></div>
      <input type="submit" value="Upload" />
    </form>
  `);
});

app.post('/api/upload', (req, res, next) => {
  const form = formidable({});

  form.parse(req, (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    res.json({ fields, files });
  });
});

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000 ...');
});

使用 Koa

import Koa from 'Koa';
import formidable from 'formidable';

const app = new Koa();

app.on('error', (err) => {
  console.error('server error', err);
});

app.use(async (ctx, next) => {
  if (ctx.url === '/api/upload' && ctx.method.toLowerCase() === 'post') {
    const form = formidable({});

    await new Promise((resolve, reject) => {
      form.parse(ctx.req, (err, fields, files) => {
        if (err) {
          reject(err);
          return;
        }

        ctx.set('Content-Type', 'application/json');
        ctx.status = 200;
        ctx.state = { fields, files };
        ctx.body = JSON.stringify(ctx.state, null, 2);
        resolve();
      });
    });
    await next();
    return;
  }

  ctx.set('Content-Type', 'text/html');
  ctx.status = 200;
  ctx.body = `
    <h2>With <code>"koa"</code> npm package</h2>
    <form action="/api/upload" enctype="multipart/form-data" method="post">
    <div>Text field title: <input type="text" name="title" /></div>
    <div>File: <input type="file" name="koaFiles" multiple="multiple" /></div>
    <input type="submit" value="Upload" />
    </form>
  `;
});

app.use((ctx) => {
  console.log('The next middleware is called');
  console.log('Results:', ctx.state);
});

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000 ...');
});

3. 项目API使用文档

Formidable / IncomingForm

formidable 模块提供了 Formidable 类,用于处理表单数据解析。以下是创建 Formidable 实例的示例:

import formidable from 'formidable';
const form = formidable(options);

Options

options 参数用于配置 Formidable 实例的行为。以下是一些常用的选项:

  • options.encoding {string} - 设置表单字段的编码格式,默认为 'utf-8'
  • options.uploadDir {string} - 设置文件上传的目录,默认为系统的临时目录。
  • options.keepExtensions {boolean} - 是否保留文件的扩展名,默认为 false
  • options.maxFileSize {number} - 设置文件上传的最大大小,默认为 200 * 1024 * 1024(200MB)。
  • options.multiples {boolean} - 是否允许多文件上传,默认为 false

方法

  • form.parse(req, callback) - 解析传入的请求对象 req,并在解析完成后调用 callback 函数。
  • form.onPart(part) - 处理多部分请求的每个部分。

4. 项目安装方式

通过 npm 安装

npm install formidable

通过 yarn 安装

yarn add formidable

选择版本

  • 安装 v2 版本:
    npm install formidable@v2
    
  • 安装 v3 版本:
    npm install formidable@v3
    

通过以上步骤,您可以成功安装并使用 formidable 模块来处理文件上传和表单数据解析。

登录后查看全文
热门项目推荐

热门内容推荐

最新内容推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
261
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
861
511
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
259
300
kernelkernel
deepin linux kernel
C
22
5
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
596
57
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
398
371
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
332
1.08 K