aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/multipart.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/multipart.js')
-rw-r--r--src/multipart.js47
1 files changed, 47 insertions, 0 deletions
diff --git a/src/multipart.js b/src/multipart.js
new file mode 100644
index 0000000..7b994cc
--- /dev/null
+++ b/src/multipart.js
@@ -0,0 +1,47 @@
1/* jshint node:true */
2
3'use strict';
4
5var multiparty = require('multiparty'),
6 timeout = require('connect-timeout');
7
8function _mime(req) {
9 var str = req.headers['content-type'] || '';
10 return str.split(';')[0];
11}
12
13module.exports = function multipart(options) {
14 return function (req, res, next) {
15 if (_mime(req) !== 'multipart/form-data') return res.status(400).send('Invalid content-type. Expecting multipart');
16
17 var form = new multiparty.Form({
18 uploadDir: '/tmp',
19 keepExtensions: true,
20 maxFieldsSize: options.maxFieldsSize || (2 * 1024), // only field size, not files
21 limit: options.limit || '500mb', // file sizes
22 autoFiles: true
23 });
24
25 // increase timeout of file uploads by default to 3 mins
26 if (req.clearTimeout) req.clearTimeout(); // clear any previous installed timeout middleware
27
28 timeout(options.timeout || (3 * 60 * 1000))(req, res, function () {
29 req.fields = { };
30 req.files = { };
31
32 form.parse(req, function (err, fields, files) {
33 if (err) return res.status(400).send('Error parsing request');
34 next(null);
35 });
36
37 form.on('file', function (name, file) {
38 req.files[name] = file;
39 });
40
41 form.on('field', function (name, value) {
42 req.fields[name] = value; // otherwise fields.name is an array
43 });
44 });
45 };
46};
47