Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

multiparty

pillarjs1.9mMIT4.2.3TypeScript support: definitely-typed

multipart/form-data parser which supports streaming

file, upload, formidable, stream, s3

readme

multiparty

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Parse http requests with content-type multipart/form-data, also known as file uploads.

See also busboy - a faster alternative which may be worth looking into.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

npm install multiparty

Usage

Parse an incoming multipart/form-data request.

var multiparty = require('multiparty');
var http = require('http');
var util = require('util');

http.createServer(function(req, res) {
  if (req.url === '/upload' && req.method === 'POST') {
    // parse a file upload
    var form = new multiparty.Form();

    form.parse(req, function(err, fields, files) {
      res.writeHead(200, { 'content-type': 'text/plain' });
      res.write('received upload:\n\n');
      res.end(util.inspect({ fields: fields, files: files }));
    });

    return;
  }

  // show a file upload form
  res.writeHead(200, { 'content-type': 'text/html' });
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(8080);

API

multiparty.Form

var form = new multiparty.Form(options)

Creates a new form. Options:

  • encoding - sets encoding for the incoming form fields. Defaults to utf8.
  • maxFieldsSize - Limits the amount of memory all fields (not files) can allocate in bytes. If this value is exceeded, an error event is emitted. The default size is 2MB.
  • maxFields - Limits the number of fields that will be parsed before emitting an error event. A file counts as a field in this case. Defaults to 1000.
  • maxFilesSize - Only relevant when autoFiles is true. Limits the total bytes accepted for all files combined. If this value is exceeded, an error event is emitted. The default is Infinity.
  • autoFields - Enables field events and disables part events for fields. This is automatically set to true if you add a field listener.
  • autoFiles - Enables file events and disables part events for files. This is automatically set to true if you add a file listener.
  • uploadDir - Only relevant when autoFiles is true. The directory for placing file uploads in. You can move them later using fs.rename(). Defaults to os.tmpdir().

form.parse(request, [cb])

Parses an incoming node.js request containing form data.This will cause form to emit events based off the incoming request.

var count = 0;
var form = new multiparty.Form();

// Errors may be emitted
// Note that if you are listening to 'part' events, the same error may be
// emitted from the `form` and the `part`.
form.on('error', function(err) {
  console.log('Error parsing form: ' + err.stack);
});

// Parts are emitted when parsing the form
form.on('part', function(part) {
  // You *must* act on the part by reading it
  // NOTE: if you want to ignore it, just call "part.resume()"

  if (part.filename === undefined) {
    // filename is not defined when this is a field and not a file
    console.log('got field named ' + part.name);
    // ignore field's content
    part.resume();
  }

  if (part.filename !== undefined) {
    // filename is defined when this is a file
    count++;
    console.log('got file named ' + part.name);
    // ignore file's content here
    part.resume();
  }

  part.on('error', function(err) {
    // decide what to do
  });
});

// Close emitted after form parsed
form.on('close', function() {
  console.log('Upload completed!');
  res.setHeader('text/plain');
  res.end('Received ' + count + ' files');
});

// Parse req
form.parse(req);

If cb is provided, autoFields and autoFiles are set to true and all fields and files are collected and passed to the callback, removing the need to listen to any events on form. This is for convenience when you want to read everything, but be sure to write cleanup code, as this will write all uploaded files to the disk, even ones you may not be interested in.

form.parse(req, function(err, fields, files) {
  Object.keys(fields).forEach(function(name) {
    console.log('got field named ' + name);
  });

  Object.keys(files).forEach(function(name) {
    console.log('got file named ' + name);
  });

  console.log('Upload completed!');
  res.setHeader('text/plain');
  res.end('Received ' + files.length + ' files');
});

fields is an object where the property names are field names and the values are arrays of field values.

files is an object where the property names are field names and the values are arrays of file objects.

form.bytesReceived

The amount of bytes received for this form so far.

form.bytesExpected

The expected number of bytes in this form.

Events

'error' (err)

Unless you supply a callback to form.parse, you definitely want to handle this event. Otherwise your server will crash when users submit bogus multipart requests!

Only one 'error' event can ever be emitted, and if an 'error' event is emitted, then 'close' will not be emitted.

If the error would correspond to a certain HTTP response code, the err object will have a statusCode property with the value of the suggested HTTP response code to send back.

Note that an 'error' event will be emitted both from the form and from the current part.

'part' (part)

Emitted when a part is encountered in the request. part is a ReadableStream. It also has the following properties:

  • headers - the headers for this part. For example, you may be interested in content-type.
  • name - the field name for this part
  • filename - only if the part is an incoming file
  • byteOffset - the byte offset of this part in the request body
  • byteCount - assuming that this is the last part in the request, this is the size of this part in bytes. You could use this, for example, to set the Content-Length header if uploading to S3. If the part had a Content-Length header then that value is used here instead.

Parts for fields are not emitted when autoFields is on, and likewise parts for files are not emitted when autoFiles is on.

part emits 'error' events! Make sure you handle them.

'aborted'

Emitted when the request is aborted. This event will be followed shortly by an error event. In practice you do not need to handle this event.

'progress' (bytesReceived, bytesExpected)

Emitted when a chunk of data is received for the form. The bytesReceived argument contains the total count of bytes received for this form so far. The bytesExpected argument contains the total expected bytes if known, otherwise null.

'close'

Emitted after all parts have been parsed and emitted. Not emitted if an error event is emitted.

If you have autoFiles on, this is not fired until all the data has been flushed to disk and the file handles have been closed.

This is typically when you would send your response.

'file' (name, file)

By default multiparty will not touch your hard drive. But if you add this listener, multiparty automatically sets form.autoFiles to true and will stream uploads to disk for you.

The max bytes accepted per request can be specified with maxFilesSize.

  • name - the field name for this file
  • file - an object with these properties:
    • fieldName - same as name - the field name for this file
    • originalFilename - the filename that the user reports for the file
    • path - the absolute path of the uploaded file on disk
    • headers - the HTTP headers that were sent along with this file
    • size - size of the file in bytes

'field' (name, value)

  • name - field name
  • value - string field value

License

MIT

changelog

4.2.3 / 2022-01-20

  • Fix handling of unquoted values in Content-Disposition
  • deps: http-errors@~1.8.1

4.2.2 / 2020-07-27

  • Fix empty files on Node.js 14.x
  • Fix form emitting aborted error after close
  • Replace fd-slicer module with internal transform stream
  • deps: http-errors@~1.8.0
  • deps: safe-buffer@5.2.1

4.2.1 / 2018-08-12

  • Use uid-safe module to for temp file names
  • deps: fd-slicer@1.1.0
  • deps: http-errors@~1.7.0

4.2.0 / 2018-07-30

  • Use http-errors for raised errors
  • Use random-bytes module for polyfill
  • perf: remove parameter reassignment

4.1.4 / 2018-05-11

  • Fix file extension filtering stopping on certain whitespace characters
  • Use safe-buffer for improved API safety
  • perf: enable strict mode

4.1.3 / 2017-01-22

4.1.2 / 2015-05-09

  • Do not emit error on part prior to emitting part
  • Fix filename with quotes truncating from certain clients

4.1.1 / 2015-01-18

  • Do not clobber existing temporary files

4.1.0 / 2014-12-04

4.0.0 / 2014-10-14

  • part events for fields no longer fire if autoFields is on
  • part events for files no longer fire if autoFiles is on
  • field, file, and part events are guaranteed to emit in the correct order - the order that the user places the parts in the request. Each part end event is guaranteed to emit before the next part event is emitted.
  • Drop Node.js 0.8.x support
  • Improve random temp file names
    • Now using 18 bytes of randomness instead of 8.
  • More robust maxFilesSize implementation
    • Before it was possible for race conditions to cause more than maxFilesSize bytes to get written to disk. That is now fixed.
  • Now part objects emit error events
    • This makes streaming work better since the part stream will emit an error when it is no longer streaming.
  • Remove support for generating the hash digest of a part
    • If you want this, do it in your own code.
  • Remove undocumented ws property from file objects
  • Require the close boundary
    • This makes multiparty more RFC-compliant and makes some invalid requests which used to work, now emit an error instead.

3.3.2 / 2014-08-07

  • Do not invoke callback after close
  • Share callback ending logic between error and close

3.3.1 / 2014-07-22

  • Remove problematic test fixtures

3.3.0 / 2014-07-03

  • Always emit close after all parts ended

3.2.10 / 2014-07-03

  • Fix callback hang in node.js 0.8 on errors
  • Remove execute bit from files

3.2.9 / 2014-06-16

  • Fix attaching error listeners directly after form.parse
  • Fix to not synchronously invoke callback to form.parse on error

3.2.8 / 2014-06-01

  • Fix developer accidentally corrupting data
  • Fix handling epilogue in a separate chunk
  • Fix initial check errors to use supplied callback

3.2.7 / 2014-05-26

  • Fix errors hanging responses in callback-style

3.2.6 / 2014-05-13

  • Fix maxFields to error on field after max

3.2.5 / 2014-05-11

  • Support boundary containing equal sign

3.2.4 / 2014-03-26

  • Keep part.byteCount undefined in chunked encoding
  • Fix temp files not always cleaned up

3.2.3 / 2014-02-20

  • Improve parsing boundary attribute from Content-Type

3.2.2 / 2014-01-29

  • Fix error on empty payloads

3.2.1 / 2014-01-27

  • Fix maxFilesSize overcalculation bug

3.2.0 / 2014-01-17

  • Add maxFilesSize for autoFiles

3.1.2 / 2014-01-13

  • Fix incorrectly using autoFields value for autoFiles

3.1.1 / 2013-12-13

  • Fix not emitting close after all part end events

3.1.0 / 2013-11-10

  • Support UTF-8 filename in Content-Disposition

3.0.0 / 2013-10-25

  • form.parse callback API changed in a compatibility-breaking manner

2.2.0 / 2013-10-15

  • Add callback API to support multiple files with same field name
  • Fix assertion crash when max field count is exceeded
  • Fix assertion crash when client aborts an invalid request
  • Fix assertion crash when EMFILE occurrs
  • Switch from assertions to only error events
  • Unpipe the request when an error occurs to save resources
  • Update readable-stream to ~1.1.9

2.1.9 / 2013-10-06

  • relax Content-Type detection regex

2.1.8 / 2013-08-26

  • Replace deprecated Buffer.write()

2.1.7 / 2013-05-23

  • Add repository field to package.json

2.1.6 / 2013-04-30

  • Expose hash as an option to Form

2.1.5 / 2013-04-10

  • Fix possible close event before all temp files are done

2.1.4 / 2013-04-09

  • Fix crash for invalid requests

2.1.3 / 2013-04-09

  • Add file.size

2.1.2 / 2013-04-08

  • Add proper backpressure support

2.1.1 / 2013-04-05

  • Add part.byteCount and part.byteOffset
  • Fix uploads larger than 2KB

2.1.0 / 2013-04-04

  • Complete rewrite. See README for changes and new API.

2.0.0 / 2013-04-02

  • Fork and rewrite from formidable