multipart/form-data parser which supports streaming
Parse http requests with content-type
multipart/form-data, also known as file uploads.
- This module uses the Node.js v0.10 streams properly
- It will not create a temp file for you unless you want it to.
- Counts bytes and does math to help you figure out the
Content-Lengthof the final part.
- You can stream uploads to s3 with aws-sdk, for example.
- Less bugs. This code is simpler, has all deprecated functionality removed, has cleaner tests, and does not try to do anything beyond multipart stream parsing.
npm install multiparty
- See examples.
Parse an incoming
var multiparty = require'multiparty';var http = require'http';var util = require'util';httpcreateServerif requrl === '/upload' && reqmethod === 'POST'// parse a file uploadvar form = ;formparsereqreswriteHead200 'content-type': 'text/plain';reswrite'received upload:\n\n';resendutilinspectfields: fields files: files;;return;// show a file upload formreswriteHead200 'content-type': 'text/html';resend'<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>';listen8080;
var form = options
Creates a new form. Options:
encoding- sets encoding for the incoming form fields. Defaults to
maxFieldsSize- Limits the amount of memory all fields (not files) can allocate in bytes. If this value is exceeded, an
errorevent is emitted. The default size is 2MB.
maxFields- Limits the number of fields that will be parsed before emitting an
errorevent. A file counts as a field in this case. Defaults to 1000.
maxFilesSize- Only relevant when
true. Limits the total bytes accepted for all files combined. If this value is exceeded, an
errorevent is emitted. The default is
fieldevents and disables
partevents for fields. This is automatically set to
trueif you add a
fileevents and disables
partevents for files. This is automatically set to
trueif you add a
uploadDir- Only relevant when
true. The directory for placing file uploads in. You can move them later using
fs.rename(). Defaults to
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 = ;// 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`.formon'error'console.log'Error parsing form: ' + errstack;;// Parts are emitted when parsing the formformon'part'// You *must* act on the part by reading it// NOTE: if you want to ignore it, just call "part.resume()"if partfilename === null// filename is "null" when this is a field and not a fileconsole.log'got field named ' + partname;// ignore field's contentpartresume;if partfilename !== null// filename is not "null" when this is a filecount++;console.log'got file named ' + partname;// ignore file's content herepartresume;parton'error'// decide what to do;;// Close emitted after form parsedformon'close'console.log'Upload completed!';ressetHeader'text/plain';resend'Received ' + count + ' files';;// Parse reqformparsereq;
cb is provided,
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.
formparsereqObjectkeysfieldsforEachconsole.log'got field named ' + name;;ObjectkeysfilesforEachconsole.log'got file named ' + name;;console.log'Upload completed!';ressetHeader'text/plain';resend'Received ' + fileslength + ' 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.
The amount of bytes received for this form so far.
The expected number of bytes in this form.
Unless you supply a callback to
form.parse, you definitely want to handle
this event. Otherwise your server will crash when users submit bogus
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
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
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
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-Lengthheader if uploading to S3. If the part had a
Content-Lengthheader 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.
Emitted when the request is aborted. This event will be followed shortly
error event. In practice you do not need to handle this event.
Emitted after all parts have been parsed and emitted. Not emitted if an
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.
By default multiparty will not touch your hard drive. But if you add this
listener, multiparty automatically sets
true and will
stream uploads to disk for you.
The max bytes accepted per request can be specified with
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
name- field name
value- string field value