1 # multiparty [![Build Status](https://travis-ci.org/andrewrk/node-multiparty.svg?branch=master)](https://travis-ci.org/andrewrk/node-multiparty) [![NPM version](https://badge.fury.io/js/multiparty.svg)](http://badge.fury.io/js/multiparty)
3 Parse http requests with content-type `multipart/form-data`, also known as file uploads.
5 See also [busboy](https://github.com/mscdex/busboy) - a
6 [faster](https://github.com/mscdex/dicer/wiki/Benchmarks) alternative
7 which may be worth looking into.
11 * This module uses the Node.js v0.10 streams properly, *even in Node.js v0.8*
12 * It will not create a temp file for you unless you want it to.
13 * Counts bytes and does math to help you figure out the `Content-Length` of
15 * You can easily stream uploads to s3 with
16 [knox](https://github.com/LearnBoost/knox), for [example](examples/s3.js).
17 * Less bugs. This code is simpler, has all deprecated functionality removed,
18 has cleaner tests, and does not try to do anything beyond multipart stream
24 npm install multiparty
29 * See [examples](examples).
31 Parse an incoming `multipart/form-data` request.
34 var multiparty = require('multiparty')
35 , http = require('http')
36 , util = require('util')
38 http.createServer(function(req, res) {
39 if (req.url === '/upload' && req.method === 'POST') {
40 // parse a file upload
41 var form = new multiparty.Form();
43 form.parse(req, function(err, fields, files) {
44 res.writeHead(200, {'content-type': 'text/plain'});
45 res.write('received upload:\n\n');
46 res.end(util.inspect({fields: fields, files: files}));
52 // show a file upload form
53 res.writeHead(200, {'content-type': 'text/html'});
55 '<form action="/upload" enctype="multipart/form-data" method="post">'+
56 '<input type="text" name="title"><br>'+
57 '<input type="file" name="upload" multiple="multiple"><br>'+
58 '<input type="submit" value="Upload">'+
68 var form = new multiparty.Form(options)
70 Creates a new form. Options:
72 * `encoding` - sets encoding for the incoming form fields. Defaults to `utf8`.
73 * `maxFieldsSize` - Limits the amount of memory a field (not a file) can
74 allocate in bytes. If this value is exceeded, an `error` event is emitted.
75 The default size is 2MB.
76 * `maxFields` - Limits the number of fields that will be parsed before
77 emitting an `error` event. A file counts as a field in this case.
79 * `maxFilesSize` - Only relevant when `autoFiles` is `true`. Limits the
80 total bytes accepted for all files combined. If this value is exceeded,
81 an `error` event is emitted. The default is `Infinity`.
82 * `autoFields` - Enables `field` events. This is automatically set to `true`
83 if you add a `field` listener.
84 * `autoFiles` - Enables `file` events. This is automatically set to `true`
85 if you add a `file` listener.
86 * `uploadDir` - Only relevant when `autoFiles` is `true`. The directory for
87 placing file uploads in. You can move them later using `fs.rename()`.
88 Defaults to `os.tmpDir()`.
89 * `hash` - Only relevant when `autoFiles` is `true`. If you want checksums
90 calculated for incoming files, set this to either `sha1` or `md5`.
93 #### form.parse(request, [cb])
95 Parses an incoming node.js `request` containing form data.This will cause
96 `form` to emit events based off the incoming request.
100 var form = new multiparty.Form();
102 // Errors may be emitted
103 form.on('error', function(err) {
104 console.log('Error parsing form: ' + err.stack);
107 // Parts are emitted when parsing the form
108 form.on('part', function(part) {
109 // You *must* act on the part by reading it
110 // NOTE: if you want to ignore it, just call "part.resume()"
112 if (part.filename === null) {
113 // filename is "null" when this is a field and not a file
114 console.log('got field named ' + part.name);
115 // ignore field's content
119 if (part.filename !== null) {
120 // filename is not "null" when this is a file
122 console.log('got file named ' + part.name);
123 // ignore file's content here
128 // Close emitted after form parsed
129 form.on('close', function() {
130 console.log('Upload completed!');
131 res.setHeader('text/plain');
132 res.end('Received ' + count + ' files');
140 If `cb` is provided, `autoFields` and `autoFiles` are set to `true` and all
141 fields and files are collected and passed to the callback, removing the need to
142 listen to any events on `form`. This is for convenience when wanted to read
143 everything, but be careful as this will write all uploaded files to the disk,
144 even ones you may not be interested in.
147 form.parse(req, function(err, fields, files) {
148 Object.keys(fields).forEach(function(name) {
149 console.log('got field named ' + name);
152 Object.keys(files).forEach(function(name) {
153 console.log('got file named ' + name);
156 console.log('Upload completed!');
157 res.setHeader('text/plain');
158 res.end('Received ' + files.length + ' files');
162 `fields` is an object where the property names are field names and the values
163 are arrays of field values.
165 `files` is an object where the property names are field names and the values
166 are arrays of file objects.
168 #### form.bytesReceived
170 The amount of bytes received for this form so far.
172 #### form.bytesExpected
174 The expected number of bytes in this form.
180 Unless you supply a callback to `form.parse`, you definitely want to handle
181 this event. Otherwise your server *will* crash when users submit bogus
184 Only one 'error' event can ever be emitted, and if an 'error' event is
185 emitted, then 'close' will not be emitted.
189 Emitted when a part is encountered in the request. `part` is a
190 `ReadableStream`. It also has the following properties:
192 * `headers` - the headers for this part. For example, you may be interested
194 * `name` - the field name for this part
195 * `filename` - only if the part is an incoming file
196 * `byteOffset` - the byte offset of this part in the request body
197 * `byteCount` - assuming that this is the last part in the request,
198 this is the size of this part in bytes. You could use this, for
199 example, to set the `Content-Length` header if uploading to S3.
200 If the part had a `Content-Length` header then that value is used
205 Emitted when the request is aborted. This event will be followed shortly
206 by an `error` event. In practice you do not need to handle this event.
208 #### 'progress' (bytesReceived, bytesExpected)
212 Emitted after all parts have been parsed and emitted. Not emitted if an `error`
213 event is emitted. This is typically when you would send your response.
215 #### 'file' (name, file)
217 **By default multiparty will not touch your hard drive.** But if you add this
218 listener, multiparty automatically sets `form.autoFiles` to `true` and will
219 stream uploads to disk for you.
221 **The max bytes accepted per request can be specified with `maxFilesSize`.**
223 * `name` - the field name for this file
224 * `file` - an object with these properties:
225 - `fieldName` - same as `name` - the field name for this file
226 - `originalFilename` - the filename that the user reports for the file
227 - `path` - the absolute path of the uploaded file on disk
228 - `headers` - the HTTP headers that were sent along with this file
229 - `size` - size of the file in bytes
231 If you set the `form.hash` option, then `file` will also contain a `hash`
232 property which is the checksum of the file.
234 #### 'field' (name, value)
236 * `name` - field name
237 * `value` - string field value