The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem.
The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem.
A Node.js module for parsing form data, especially file uploads.
[![Code style][codestyle-img]][codestyle-url] [![linux build status][linux-build-img]][build-url] [![macos build status][macos-build-img]][build-url]
If you have any how-to kind of questions, please read the [Contributing
Guide][contributing-url] and [Code of Conduct][code_of_conduct-url]
documents.
For bugs reports and feature requests, [please create an
issue][open-issue-url] or ping [@wgw_eth / @wgw_lol][twitter-url]
at Twitter.
[![Conventional Commits][ccommits-img]][ccommits-url] [![Minimum Required Nodejs][nodejs-img]][npmv-url] [![Buy me a Kofi][kofi-img]][kofi-url] [![Make A Pull Request][prs-welcome-img]][prs-welcome-url]
This project is semantically versioned and if you want support in migrating between versions you can schedule us for training or support us through donations, so we can prioritize.
[!CAUTION] As of April 2025, old versions like v1 and v2 are still the most used, while they are deprecated for years -- they are also vulnerable to attacks if you are not implementing it properly. Please upgrade! We are here to help, and AI Editors & Agents could help a lot in such codemod-like migrations.
[!TIP] If you are starting a fresh project, you can check out the
formidable-miniwhich is a super minimal version of Formidable (not quite configurable yet, but when it does it could become the basis forformidable@v4), using web standards like FormData API and File API, and you can use it to stream uploads directly to S3 or other such services.
[![][npm-weekly-img]][npmv-url] [![][npm-monthly-img]][npmv-url] [![][npm-yearly-img]][npmv-url] [![][npm-alltime-img]][npmv-url]
[!NOTE] Check VERSION NOTES for more information on v1, v2, and v3 plans, NPM dist-tags and branches._
This module was initially developed by @felixge for Transloadit, a service focused on uploading and encoding images and videos. It has been battle-tested against hundreds of GBs of file uploads from a large variety of clients and is considered production-ready and is used in production for years.
Currently, we are few maintainers trying to deal with it. :) More contributors are always welcome! :heart: Jump on issue #412 which is closed, but if you are interested we can discuss it and add you after strict rules, like enabling Two-Factor Auth in your npm and GitHub accounts.
options.fileWriteStreamHandler)This package is a dual ESM/commonjs package.
[!NOTE] This project requires
Node.js >= 20. Install it using yarn or npm.
We highly recommend to use Yarn when you think to contribute to this project.
This is a low-level package, and if you're using a high-level framework it may already be included. Check the examples below and the examples/ folder.
# v2
npm install formidable@v2
# v3
npm install formidable
npm install formidable@v3Note: Future not ready releases will be published on *-next dist-tags for the corresponding version.
For more examples look at the examples/ directory.
Parse an incoming file upload, with the
Node.js's built-in http module.
…There are multiple variants to do this, but Formidable just need Node.js Request stream, so something like the following example should work just fine, without any third-party Express.js middleware.
Or try the examples/with-express.js
…Of course, with Koa v1, v2 or future v3 the things
are very similar. You can use formidable manually as shown below or through
the koa-better-body package which is
using formidable under the hood and support more features and different
request bodies, check its documentation for more info.
Note: this example is assuming Koa v2. Be aware that you should pass ctx.req
which is Node.js's Request, and NOT the ctx.request which is Koa's Request
object - there is a difference.
…The benchmark is quite old, from the old codebase. But maybe quite true though. Previously the numbers was around ~500 mb/sec. Currently with moving to the new Node.js Streams API it's faster. You can clearly see the differences between the Node versions.
Note: a lot better benchmarking could and should be done in future.
Benchmarked on 8GB RAM, Xeon X3440 (2.53 GHz, 4 cores, 8 threads)
~/github/node-formidable master
❯ nve --parallel 8 10 12 13 node benchmark/bench-multipart-parser.js
⬢ Node 8
1261.08 mb/sec
⬢ Node 10
1113.04 mb/sec
⬢ Node 12
2107.00 mb/sec
⬢ Node 13
2566.42 mb/secAll shown are equivalent.
Please pass options to the function/constructor, not by assigning
them to the instance form
import formidable from "formidable";
const form = formidable(options);See it's defaults in src/Formidable.js DEFAULT_OPTIONS
(the DEFAULT_OPTIONS constant).
options.encoding {string} - default 'utf-8'; sets encoding for
incoming form fields,
options.uploadDir {string} - default os.tmpdir(); the directory for
placing file uploads in. You can move them later by using fs.rename().
options.keepExtensions {boolean} - default false; to include the
extensions of the original files or not
options.allowEmptyFiles {boolean} - default false; allow upload empty
files
options.minFileSize {number} - default 1 (1byte); the minium size of
uploaded file.
options.maxFiles {number} - default Infinity;
limit the amount of uploaded files, set Infinity for unlimited
options.maxFileSize {number} - default 200 * 1024 * 1024 (200mb);
limit the size of each uploaded file.
options.maxTotalFileSize {number} - default options.maxFileSize;
limit the size of the batch of uploaded files.
options.maxFields {number} - default 1000; limit the number of fields, set Infinity for unlimited
options.maxFieldsSize {number} - default 20 * 1024 * 1024 (20mb);
limit the amount of memory all fields together (except files) can allocate in
bytes.
options.hashAlgorithm {string | false} - default false; include checksums calculated
for incoming files, set this to some hash algorithm, see
crypto.createHash
for available algorithms
options.fileWriteStreamHandler {function} - default null, which by
default writes to host machine file system every file parsed; The function
should return an instance of a
Writable stream
that will receive the uploaded file data. With this option, you can have any
custom behavior regarding where the uploaded file data will be streamed for.
If you are looking to write the file uploaded in other types of cloud storages
(AWS S3, Azure blob storage, Google cloud storage) or private file storage,
this is the option you're looking for. When this option is defined the default
behavior of writing the file in the host machine file system is lost.
options.filename {function} - default undefined Use it to control
newFilename. Must return a string. Will be joined with options.uploadDir.
options.filter {function} - default function that always returns true.
Use it to filter files before they are uploaded. Must return a boolean. Will not make the form.parse error
options.createDirsFromUploads {boolean} - default false. If true, makes direct folder uploads possible. Use <input type="file" name="folders" webkitdirectory directory multiple> to create a form to upload folders. Has to be used with the options options.uploadDir and options.filename where options.filename has to return a string with the character / for folders to be created. The base will be options.uploadDir.
options.filename {function} function (name, ext, part, form) -> stringwhere part can be decomposed as
const { originalFilename, mimetype } = part;Note: If this size of combined fields, or size of some file is exceeded, an
'error' event is fired.
// The amount of bytes received for this form so far.
form.bytesReceived;// The expected number of bytes in this form.
form.bytesExpected;options.filter {function} function ({name, originalFilename, mimetype}) -> booleanBehaves like Array.filter: Returning false will simply ignore the file and go to the next.
const options = {
filter: function ({ name, originalFilename, mimetype }) {
// keep only images
return mimetype && mimetype.includes("image");
},
};Note: use an outside variable to cancel all uploads upon the first error
Note: use form.emit('error') to make form.parse error
let cancelUploads = false; // create variable at the same scope as form
const options = {
filter: function ({ name, originalFilename, mimetype }) {
// keep only images
const valid = mimetype && mimetype.includes("image");
if (!valid) {
form.emit("error", new formidableErrors.default("invalid type", 0, 400)); // optional make form.parse error
cancelUploads = true; //variable to make filter return false after the first problem
}
return valid && !cancelUploads;
},
};Parses an incoming Node.js request containing form data. If callback is not provided a promise is returned.
const form = formidable({ uploadDir: __dirname });
form.parse(req, (err, fields, files) => {
console.log("fields:", fields);
console.log("files:", files);
});
// with Promise
const [fields, files] = await form.parse(req);You may overwrite this method if you are interested in directly accessing the
multipart stream. Doing so will disable any 'field' / 'file' events
processing which would occur otherwise, making you fully responsible for
handling the processing.
About uploadDir, given the following directory structure
project-name
├── src
│ └── server.js
│
└── uploads
└── image.jpg__dirname would be the same directory as the source file itself (src)
`${__dirname}/../uploads`;to put files in uploads.
Omitting __dirname would make the path relative to the current working directory. This would be the same if server.js is launched from src but not project-name.
null will use default which is os.tmpdir()
Note: If the directory does not exist, the uploaded files are silently discarded. To make sure it exists:
import { createNecessaryDirectoriesSync } from "filesac";
const uploadPath = `${__dirname}/../uploads`;
createNecessaryDirectoriesSync(`${uploadPath}/x`);In the example below,
Maintainer Wanted
Multipart parsing does not ignore CRLF in base64 properly
Bug: JSON parser incorrectly triggered by "json" in multipart boundary
Add virus scanning example to documentation
Question: How to use inside Google Cloud Run?
Attaching 'data' listeners immediately
Specific file names cause the extension to not be set correctly with options.keepExtensions "test(.123).pdf"
trimmed v3 benchmarks
Convert 'firstValues' helper into an option for Formidable constructor.
maxFileSize not working as it should