1.4.2 • Published 1 day ago

multer v1.4.2

Weekly downloads
811,088
License
MIT
Repository
github
Last release
1 day ago

Multer Build Status 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).

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:

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

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

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 can use the .none() method, example:

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

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

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

API

File information

Each file contains the following information:

KeyDescription
fieldNameField name specified in the form
originalNameName of the file on the user's computer (undefined if no filename was supplied by the client)
sizeSize of the file in bytes
streamStream of file
detectedMimeTypeThe detected mime-type, or null if we failed to detect
detectedFileExtensionThe typical file extension for files of the detected type, or empty string if we failed to detect (with leading . to match path.extname)
clientReportedMimeTypeThe mime type reported by the client using the Content-Type header, or null1 if the header was absent
clientReportedFileExtensionThe extension of the file uploaded (as reported by path.extname)

1 Currently returns text/plain if header is absent, this is a bug and it will be fixed in a patch release. Do not rely on this behavior.

multer(opts)

Multer accepts an options object, the following are the options that can be passed to Multer.

KeyDescription
limitsLimits of the uploaded data (full description)

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

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.

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.

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

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err) {
      // An error occurred when uploading
      return
    }

    // Everything went fine
  })
})
unleashed-apizuant_back_end@determapp/editor-http-serverreact-pathway-mapper@back4app/back4appgraphql-authentification-servicect-platform-backendscreen-spec-mdbidouanode-excel-uploadcms-vision.jsrpi-express_apicommie-servicersn-node-corehydroniumbicoesite-biportal-demotypescript-node-express-starter-simplifiedlur-core@injectable/express-serviceffmpeg-test-editing-montages-and-transitionsunoconv-serverzync-adminangular2-components-lib@cotype/core@colabo-media/b-upload@colabo-media/media-upload@codewitchbella/file-upload@collaveinc/workbench-server@commonshost/coretry-skeleton@emigrup/edk-coretransformationservicetree-house-storage@edenjs/cli@edenjs/frameworktreenote@dadi/webtovolt@douzhi/databasetourneetrailpack-proxy-permissionstrailpack-proxy-carttravis-config-server@dev-volpy/typescript-rest@devcms/core@digitalmomentum/storagewave-routing-controllersweather-graphqlwebda-shellwebpack-dev-mockwiser@labshare/request-tracking-api@jinyexin/core@klurdy/core@klurdy/libs@klurdy/merchants@klurdy/orders@klurdy/products@klurdy/users@koa-framework/koa-multer@li_shengyou/xmysql@lebaotrung/uploadfile@kos-ng-it-konsult/uploader@laomu/npm-proxy@leizm/hhh@linaframework/commonvikingvikingcms@harvestr-api/integration-s3@http2/apivtuzxvtuzx-web@icapps/tree-house-storageversion-repo-nodevenustech-node-server@ha4us/rest.adapter@ha4us/adapter.restviz-project-servervideo-servervineyard-cellar@hatsa/expressvorlon@hopgoldy/auto-gitvtc-cmsvmext@hke/ms-fileservicewodax-umi-mockx-swagger-toolsxmysqlyaasyabaaszipwire-nodezwbasezvonok@ionaai/iranlptemplatezombie-ghost-cmszoster@iproxy/whistlezsysbztachi
2.0.0-rc.1

1 day ago

2.0.0-beta.1

3 months ago

1.4.2

8 months ago

2.0.0-alpha.7

10 months ago

1.4.1

1 year ago

1.4.0

1 year ago

1.3.1

2 years ago

2.0.0-alpha.6

3 years ago

2.0.0-alpha.5

3 years ago

2.0.0-alpha.4

3 years ago

1.3.0

3 years ago

2.0.0-alpha.3

3 years ago

1.2.1

3 years ago

2.0.0-alpha.2

3 years ago

2.0.0-alpha.1

3 years ago

1.2.0

4 years ago

1.1.0

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago

0.1.8

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago