multer

Middleware for handling multipart/form-data.

Multer

Multer is a node.js middleware for handling multipart/form-data. It is written on top of busboy for maximum efficiency.

npm install --save multer
var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })
 
var app = express()
 
app.post('/profile', upload.single('avatar'), function (reqresnext) {
  // req.file is the `avatar` file 
})
 
app.post('/photos/upload', upload.array('photos', 12), function (reqresnext) {
  // req.files is array of `photos` files 
})
 
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (reqresnext) {
  // 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 
})

You can access post data fields as body on the request object:

console.log(req.body)

IMPORTANT: Multer will only process forms which are of the type multipart/form-data.

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 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 file will be renamed and uploaded to the temporary directory of the system.

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

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

app.use(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.

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

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.

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 }
]

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

var storage = multer.diskStorage({
  destinationfunction (reqfilecb) {
    cb(null, '/tmp/my-uploads')
  },
  filenamefunction (reqfilecb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
 
app.use(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').

filename is used to determine what the file should be named inside the folder.

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.

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

var storage = multer.memoryStorage()
 
app.use(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.

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 size1MB
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.

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 (reqfilecb) {
 
  // 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!'))
 
}

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 (reqres) {
  upload(req, res, function (err) {
    if (err) {
      // An error occurred when uploading 
      return
    }
 
    // Everything went fine 
  })
})

See the documentation here if you want to build your own storage engine.

MIT