Convert Figma logo to code with AI

expressjs logomulter

Node.js middleware for handling `multipart/form-data`.

11,647
1,060
11,647
266

Top Related Projects

Simple express file upload middleware that wraps around busboy

2,850

A streaming parser for HTML form data for node.js

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.

A node.js module for parsing multipart-form data requests which supports streams2

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.

Quick Overview

Multer is a popular Node.js middleware for handling multipart/form-data, primarily used for uploading files. It is designed to work seamlessly with Express and similar web application frameworks, making file uploads easy to manage and integrate into web applications.

Pros

  • Easy to use and integrate with Express applications
  • Supports multiple file uploads
  • Provides flexible storage options (disk storage, memory storage, custom storage engines)
  • Offers file filtering capabilities

Cons

  • Limited to handling multipart/form-data only
  • Doesn't handle non-multipart form data
  • Requires additional configuration for security measures
  • May have performance issues with very large files

Code Examples

  1. Basic file upload:
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

const app = express();

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully');
});
  1. Multiple file upload:
const upload = multer({ dest: 'uploads/' });

app.post('/upload-multiple', upload.array('files', 5), (req, res) => {
  res.send(`${req.files.length} files uploaded successfully`);
});
  1. Custom file name and storage:
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage });

Getting Started

  1. Install Multer:
npm install multer
  1. Set up a basic Express app with Multer:
const express = require('express');
const multer = require('multer');
const app = express();

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

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully');
});

app.listen(3000, () => console.log('Server started on port 3000'));
  1. Create an HTML form for file upload:
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="Upload">
</form>

Competitor Comparisons

Simple express file upload middleware that wraps around busboy

Pros of express-fileupload

  • Simpler API with less boilerplate code
  • Built-in file size limiting and file type filtering
  • Supports multiple file uploads without additional configuration

Cons of express-fileupload

  • Less actively maintained compared to Multer
  • Fewer middleware options and customization features
  • Limited support for advanced use cases like streaming uploads

Code Comparison

express-fileupload:

app.use(fileUpload());

app.post('/upload', (req, res) => {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }
  let sampleFile = req.files.sampleFile;
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err) return res.status(500).send(err);
    res.send('File uploaded!');
  });
});

Multer:

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

app.post('/upload', upload.single('myFile'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }
  res.send('File uploaded!');
});

Both libraries provide file upload functionality for Express applications, but they differ in their approach and features. express-fileupload offers a more straightforward setup with built-in file handling, while Multer provides greater flexibility and control over the upload process. The choice between the two depends on the specific requirements of your project and the level of customization needed.

2,850

A streaming parser for HTML form data for node.js

Pros of Busboy

  • More lightweight and focused on parsing multipart form data
  • Offers greater flexibility and control over parsing process
  • Can be used in non-Express.js environments

Cons of Busboy

  • Requires more manual configuration and setup
  • Less user-friendly for beginners
  • Lacks some convenience features provided by Multer

Code Comparison

Multer:

const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
  // File is available as req.file
});

Busboy:

app.post('/upload', (req, res) => {
  const busboy = new Busboy({ headers: req.headers });
  busboy.on('file', (fieldname, file, filename) => {
    // Handle file upload
  });
  req.pipe(busboy);
});

Summary

Multer is a higher-level middleware specifically designed for Express.js, offering easier setup and usage for file uploads. It provides convenient features like automatic file storage and multi-file handling.

Busboy, on the other hand, is a lower-level parser for multipart form data. It offers more flexibility and control over the parsing process but requires more manual configuration. Busboy can be used in various Node.js environments, not limited to Express.js.

Choose Multer for quick and easy file upload handling in Express.js applications, especially if you're a beginner. Opt for Busboy when you need more granular control over the parsing process or when working in non-Express.js environments.

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.

Pros of formidable

  • More flexible and can be used with various HTTP frameworks, not just Express
  • Supports parsing of both multipart and JSON data
  • Offers more granular control over file upload process

Cons of formidable

  • Requires more setup and configuration compared to multer
  • Less integrated with Express middleware ecosystem
  • May have a steeper learning curve for beginners

Code Comparison

multer:

const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
  // File is available as req.file
});

formidable:

app.post('/upload', (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, (err, fields, files) => {
    // Files are available in the files object
  });
});

Both multer and formidable are popular libraries for handling file uploads in Node.js applications. Multer is specifically designed as middleware for Express, making it easier to integrate with Express-based projects. It provides a straightforward API for handling multipart/form-data, which is commonly used for file uploads.

Formidable, on the other hand, is a more general-purpose parsing library that can handle various types of form data, including file uploads. It offers more flexibility and can be used with different HTTP frameworks, not just Express. Formidable provides more control over the parsing process and supports both multipart and JSON data.

While multer is often preferred for its simplicity and seamless integration with Express, formidable might be a better choice for projects requiring more advanced parsing capabilities or those not using Express as their web framework.

A node.js module for parsing multipart-form data requests which supports streams2

Pros of multiparty

  • More flexible and customizable for handling multipart form data
  • Supports streaming, which can be beneficial for large file uploads
  • Can handle both files and fields in a single parse operation

Cons of multiparty

  • Requires more manual configuration and setup compared to Multer
  • Less integrated with Express.js ecosystem
  • May have a steeper learning curve for beginners

Code Comparison

multiparty:

const multiparty = require('multiparty');
const form = new multiparty.Form();

form.parse(req, (err, fields, files) => {
  // Handle parsed data
});

Multer:

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

app.post('/upload', upload.single('file'), (req, res) => {
  // Handle uploaded file
});

Key Differences

  • multiparty offers more granular control over parsing and handling of multipart form data
  • Multer provides a more streamlined, Express-friendly API for file uploads
  • multiparty can handle both files and fields simultaneously, while Multer focuses primarily on file uploads
  • Multer integrates more seamlessly with Express middleware
  • multiparty may be preferred for complex scenarios or when streaming is required, while Multer is often simpler for basic file upload needs in Express applications

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.

Pros of formidable

  • More flexible and can be used with various HTTP frameworks, not just Express
  • Supports parsing of both multipart and JSON data
  • Offers more granular control over file upload process

Cons of formidable

  • Requires more setup and configuration compared to multer
  • Less integrated with Express middleware ecosystem
  • May have a steeper learning curve for beginners

Code Comparison

multer:

const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
  // File is available as req.file
});

formidable:

app.post('/upload', (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, (err, fields, files) => {
    // Files are available in the files object
  });
});

Both multer and formidable are popular libraries for handling file uploads in Node.js applications. Multer is specifically designed as middleware for Express, making it easier to integrate with Express-based projects. It provides a straightforward API for handling multipart/form-data, which is commonly used for file uploads.

Formidable, on the other hand, is a more general-purpose parsing library that can handle various types of form data, including file uploads. It offers more flexibility and can be used with different HTTP frameworks, not just Express. Formidable provides more control over the parsing process and supports both multipart and JSON data.

While multer is often preferred for its simplicity and seamless integration with Express, formidable might be a better choice for projects requiring more advanced parsing capabilities or those not using Express as their web framework.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Multer Build Status Test Coverage NPM version js-standard-style

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:

Installation

$ npm install --save 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 cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, 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 an 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

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 an 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

NPM DownloadsLast 30 Days