What is multer?
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.
What are multer's main functionalities?
File Uploads
This feature allows you to upload files to your server. The code sample demonstrates how to handle a single file upload with Multer.
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), function (req, res) {
// req.file is the `file` file
res.send('File uploaded!');
});
Multiple Files Upload
Multer also supports uploading multiple files at once. The code sample shows how to handle multiple file uploads, limiting to 12 files in this case.
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.array('files', 12), function (req, res) {
// req.files is array of `files` files
res.send('Multiple files uploaded!');
});
Disk Storage
Multer allows you to customize the storage of files. This code sample demonstrates how to use disk storage to control the storage location and file naming.
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({ storage: storage });
Memory Storage
For temporary storage or when you want to process the file without saving it to disk, you can use memory storage. The code sample shows how to store a file in memory.
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() });
app.post('/upload', upload.single('file'), function (req, res) {
// req.file is the `file` file stored in memory
res.send('File uploaded and stored in memory!');
});
File Filtering
Multer provides a way to filter out files based on conditions you set. This code sample demonstrates file filtering to only allow JPEG images.
const multer = require('multer');
const upload = multer({
fileFilter: function (req, file, cb) {
if (file.mimetype !== 'image/jpeg') {
return cb(new Error('Only JPEG files are allowed!'), false);
}
cb(null, true);
}
});
Other packages similar to multer
formidable
Formidable is an alternative to Multer for parsing form data, especially file uploads. It is less middleware-oriented and more flexible in terms of handling various form parsing tasks.
busboy
Busboy is a low-level Node.js module for parsing incoming HTML form data. Multer is built on top of Busboy, but provides a more convenient middleware API for integrating with Express.js applications.
multiparty
Multiparty is another module for handling multipart/form-data requests, which is the type of requests that file uploads usually come in. It is similar to Multer but has a different API and is used in a slightly different way.
Multer
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
).
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:
var multer = require('multer')
var express = require('express')
var app = express()
var upload = multer()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
})
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
})
In case you need to handle a text-only multipart form, you can use the .none()
method, example:
var multer = require('multer')
var express = require('express')
var app = express()
var upload = multer()
app.post('/profile', upload.none(), function (req, res, next) {
})
API
File information
Each file contains the following information:
Key | Description |
---|
fieldName | Field name specified in the form |
originalName | Name of the file on the user's computer |
size | Size of the file in bytes |
stream | Stream of file |
multer(opts)
Multer accepts an options object, the following are the options that can be
passed to Multer.
.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. This is the same as doing upload.fields([])
.
.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.
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:
Key | Description | Default |
---|
fieldNameSize | Max field name size | 100 bytes |
fieldSize | Max field value size | 1MB |
fields | Max number of non-file fields | Infinity |
fileSize | For multipart forms, the max file size (in bytes) | Infinity |
files | For multipart forms, the max number of file fields | Infinity |
parts | For multipart forms, the max number of parts (fields + files) | Infinity |
headerPairs | For multipart forms, the max number of header key=>value pairs to parse | 2000 |
Specifying the limits can help protect your site against denial of service (DoS) attacks.
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.
var upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err) {
return
}
})
})