]>
Commit | Line | Data |
---|---|---|
1 | /* jshint node:true */ | |
2 | ||
3 | 'use strict'; | |
4 | ||
5 | var multiparty = require('multiparty'), | |
6 | timeout = require('connect-timeout'); | |
7 | ||
8 | function _mime(req) { | |
9 | var str = req.headers['content-type'] || ''; | |
10 | return str.split(';')[0]; | |
11 | } | |
12 | ||
13 | module.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 |