multer vs connect-busboy vs busboy vs express-fileupload vs form-data vs formidable vs koa-body
Node.js File Upload Libraries
multerconnect-busboybusboyexpress-fileuploadform-dataformidablekoa-bodySimilar Packages:

Node.js File Upload Libraries

These libraries facilitate file uploads in Node.js applications, providing various methods to handle multipart/form-data. They differ in terms of middleware integration, performance, and feature sets, catering to different use cases and frameworks such as Express and Koa. Understanding their unique functionalities helps developers choose the right tool for their specific needs.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
multer11,159,41812,01831.5 kB2478 days agoMIT
connect-busboy28,7891564.57 kB0--
busboy02,996124 kB37--
express-fileupload01,562119 kB248 months agoMIT
form-data02,35681.2 kB1364 months agoMIT
formidable0-204 kB-a year agoMIT
koa-body095360.7 kB373 months agoMIT

Feature Comparison: multer vs connect-busboy vs busboy vs express-fileupload vs form-data vs formidable vs koa-body

Integration

  • multer:

    Multer is a middleware for Express that simplifies file uploads, providing built-in support for various storage options and configuration.

  • connect-busboy:

    Connect-Busboy integrates Busboy with Connect middleware, simplifying the process of handling file uploads in Connect-based applications.

  • busboy:

    Busboy is a low-level streaming parser that requires manual integration into your application, giving you full control over the file upload process but requiring more setup.

  • express-fileupload:

    Express-Fileupload is designed specifically for Express, providing a plug-and-play solution for file uploads with minimal configuration needed.

  • form-data:

    Form-Data is primarily used for constructing multipart/form-data requests, making it suitable for client-side applications rather than server-side file handling.

  • formidable:

    Formidable can be used with any Node.js application, providing a comprehensive solution for file uploads and form parsing, but it requires more setup than simpler libraries.

  • koa-body:

    Koa-Body integrates seamlessly with Koa, allowing for easy handling of multipart/form-data in Koa applications, with a straightforward API.

Performance

  • multer:

    Multer provides excellent performance for file uploads in Express applications, with options to store files in memory or on disk, allowing for flexible handling.

  • connect-busboy:

    Performance is similar to Busboy, as it utilizes the same underlying library, but may introduce slight overhead due to middleware integration.

  • busboy:

    Busboy is highly efficient for large file uploads due to its streaming nature, which minimizes memory usage and allows for processing files in chunks.

  • express-fileupload:

    Express-Fileupload is easy to use but may not be as performant as Busboy for very large files, as it buffers the entire file in memory before processing.

  • form-data:

    Form-Data is optimized for creating requests but is not designed for handling uploads on the server side, so performance considerations depend on the use case.

  • formidable:

    Formidable is efficient for file uploads but can consume more memory than Busboy, especially with large files, as it buffers uploads before processing.

  • koa-body:

    Koa-Body is designed for Koa applications and offers good performance, but like Express-Fileupload, it may buffer files in memory depending on configuration.

Ease of Use

  • multer:

    Multer is designed to be easy to use with Express, allowing developers to quickly set up file uploads with clear configuration options.

  • connect-busboy:

    Connect-Busboy is straightforward to use within Connect applications, providing a simple API for file uploads without much boilerplate code.

  • busboy:

    Busboy requires more manual setup and configuration, making it less beginner-friendly but offering greater control for experienced developers.

  • express-fileupload:

    Express-Fileupload is very easy to use, with minimal setup required, making it ideal for beginners or quick prototypes.

  • form-data:

    Form-Data is easy to use for constructing requests but is not focused on server-side file handling, which may require additional libraries for uploads.

  • formidable:

    Formidable has a moderate learning curve, offering comprehensive functionality but requiring more understanding of its API and options.

  • koa-body:

    Koa-Body is user-friendly for Koa applications, providing a clean API for handling file uploads and form data with minimal configuration.

File Handling Features

  • multer:

    Multer provides extensive file handling features, including storage options, file size limits, and file filtering, making it highly configurable for various use cases.

  • connect-busboy:

    Connect-Busboy inherits Busboy's file handling capabilities, allowing for streaming uploads within Connect applications.

  • busboy:

    Busboy allows for streaming file uploads, enabling developers to process files as they are being uploaded, which is useful for large files.

  • express-fileupload:

    Express-Fileupload provides simple file handling features but lacks advanced options for file processing compared to other libraries.

  • form-data:

    Form-Data focuses on creating multipart requests and does not handle file uploads on the server side, requiring additional handling for uploads.

  • formidable:

    Formidable offers robust file handling features, including file renaming, size limits, and error handling, making it suitable for complex applications.

  • koa-body:

    Koa-Body supports file uploads and provides a clean API for accessing uploaded files, making it easy to work with in Koa applications.

Community and Support

  • multer:

    Multer has a large community and is widely adopted in Express applications, ensuring good support and documentation.

  • connect-busboy:

    Connect-Busboy benefits from the Connect community, which provides support and resources for users.

  • busboy:

    Busboy has a smaller community compared to some other libraries, but it is well-maintained and widely used in production applications.

  • express-fileupload:

    Express-Fileupload has a large user base and community support, making it easy to find help and resources online.

  • form-data:

    Form-Data is widely used for constructing requests and has good community support, but it is not focused on server-side uploads.

  • formidable:

    Formidable has been around for a while and has a solid community, providing ample resources and support for developers.

  • koa-body:

    Koa-Body is part of the Koa ecosystem, which has a growing community and support for Koa-related libraries.

How to Choose: multer vs connect-busboy vs busboy vs express-fileupload vs form-data vs formidable vs koa-body

  • multer:

    Use Multer when working with Express and need a powerful middleware for handling multipart/form-data. It offers extensive configuration options for file storage and limits, making it ideal for complex file upload scenarios.

  • connect-busboy:

    Select Connect-Busboy if you are using Connect middleware and need a simple way to integrate Busboy with your existing Connect-based application. It offers a straightforward approach to handle file uploads seamlessly within Connect.

  • busboy:

    Choose Busboy for a lightweight, low-level streaming parser that is efficient for handling large file uploads without additional overhead. It is ideal for applications that require fine-grained control over file processing.

  • express-fileupload:

    Use Express-Fileupload for an easy-to-use solution that integrates directly with Express. It simplifies file upload handling with minimal setup, making it suitable for quick projects or prototypes.

  • form-data:

    Opt for Form-Data when you need to construct and send multipart/form-data requests from Node.js. It is particularly useful for client-side applications that require file uploads to a server.

  • formidable:

    Choose Formidable for a robust file upload solution that supports file uploads and form parsing. It is well-suited for applications that require detailed file handling and form data processing.

  • koa-body:

    Select Koa-Body if you are building applications with Koa and need a middleware that supports multipart/form-data. It provides a clean API for handling file uploads and form data in Koa applications.

README for multer

Multer NPM Version NPM Downloads Build Status Test Coverage OpenSSF Scorecard Badge

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

NOTE: Multer will not process any form which is not multipart (multipart/form-data).

Translations

This README is also available in other languages:

العربيةArabic
简体中文Chinese
FrançaisFrench
한국어Korean
PortuguêsPortuguese (BR)
Русский языкRussian
EspañolSpanish
O'zbek tiliUzbek
Việt NamVietnamese
TürkçeTurkish

Installation

$ npm install multer

Usage

Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

Basic usage example:

Don't forget the enctype="multipart/form-data" in your form.

<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>
const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

const uploadMiddleware = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', uploadMiddleware, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})

In case you need to handle a text-only multipart form, you should use the .none() method:

const express = require('express')
const app = express()
const multer  = require('multer')
const upload = multer()

app.post('/profile', upload.none(), function (req, res, next) {
  // req.body contains the text fields
})

Here's an example on how multer is used in a HTML form. Take special note of the enctype="multipart/form-data" and name="uploaded_file" fields:

<form action="/stats" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="uploaded_file">
    <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
    <input type="submit" value="Get me the stats!" class="btn btn-default">
  </div>
</form>

Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the name field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail:

const multer  = require('multer')
const upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
  // req.file is the name of your file in the form above, here 'uploaded_file'
  // req.body will hold the text fields, if there were any
  console.log(req.file, req.body)
});

API

File information

Each file contains the following information:

KeyDescriptionNote
fieldnameField name specified in the form
originalnameName of the file on the user's computer
encodingEncoding type of the file
mimetypeMime type of the file
sizeSize of the file in bytes
destinationThe folder to which the file has been savedDiskStorage
filenameThe name of the file within the destinationDiskStorage
pathThe full path to the uploaded fileDiskStorage
bufferA Buffer of the entire fileMemoryStorage

multer(opts)

Multer accepts an options object, the most basic of which is the dest property, which tells Multer where to upload the files. In case you omit the options object, the files will be kept in memory and never written to disk.

By default, Multer will rename the files so as to avoid naming conflicts. The renaming function can be customized according to your needs.

The following are the options that can be passed to Multer.

KeyDescription
dest or storageWhere to store the files
fileFilterFunction to control which files are accepted
limitsLimits of the uploaded data
preservePathKeep the full path of files instead of just the base name
defParamCharsetDefault character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). Default: 'latin1'

In an average web app, only dest might be required, and configured as shown in the following example.

const upload = multer({ dest: 'uploads/' })

If you want more control over your uploads, you'll want to use the storage option instead of dest. Multer ships with storage engines DiskStorage and MemoryStorage; More engines are available from third parties.

.single(fieldname)

Accept a single file with the name fieldname. The single file will be stored in req.file.

.array(fieldname[, maxCount])

Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files.

.fields(fields)

Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files.

fields should be an array of objects with name and optionally a maxCount. Example:

[
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 }
]

.none()

Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.

.any()

Accepts all files that comes over the wire. An array of files will be stored in req.files.

WARNING: Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded files.

storage

DiskStorage

The disk storage engine gives you full control on storing files to disk.

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})

const upload = multer({ storage: storage })

There are two options available, destination and filename. They are both functions that determine where the file should be stored.

destination is used to determine within which folder the uploaded files should be stored. This can also be given as a string (e.g. '/tmp/uploads'). If no destination is given, the operating system's default directory for temporary files is used.

Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you.

filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.

Note: Multer will not append any file extension for you, your function should return a filename complete with a file extension.

Each function gets passed both the request (req) and some information about the file (file) to aid with the decision.

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

For understanding the calling convention used in the callback (needing to pass null as the first param), refer to Node.js error handling

MemoryStorage

The memory storage engine stores the files in memory as Buffer objects. It doesn't have any options.

const storage = multer.memoryStorage()
const upload = multer({ storage: storage })

When using memory storage, the file info will contain a field called buffer that contains the entire file.

WARNING: Uploading very large files, or relatively small files in large numbers very quickly, can cause your application to run out of memory when memory storage is used.

limits

An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on busboy's page.

The following integer values are available:

KeyDescriptionDefault
fieldNameSizeMax field name size100 bytes
fieldSizeMax field value size (in bytes)1MB
fieldsMax number of non-file fieldsInfinity
fileSizeFor multipart forms, the max file size (in bytes)Infinity
filesFor multipart forms, the max number of file fieldsInfinity
partsFor multipart forms, the max number of parts (fields + files)Infinity
headerPairsFor multipart forms, the max number of header key=>value pairs to parse2000

Specifying the limits can help protect your site against denial of service (DoS) attacks.

fileFilter

Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this:

function fileFilter (req, file, cb) {

  // The function should call `cb` with a boolean
  // to indicate if the file should be accepted

  // To reject this file pass `false`, like so:
  cb(null, false)

  // To accept the file pass `true`, like so:
  cb(null, true)

  // You can always pass an error if something goes wrong:
  cb(new Error('I don\'t have a clue!'))

}

Error handling

When encountering an error, Multer will delegate the error to Express. You can display a nice error page using the standard express way.

If you want to catch errors specifically from Multer, you can call the middleware function by yourself. Also, if you want to catch only the Multer errors, you can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer.MulterError).

const multer = require('multer')
const upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  })
})

Custom storage engine

For information on how to build your own storage engine, see Multer Storage Engine.

License

MIT