-
Notifications
You must be signed in to change notification settings - Fork 3
/
multiparser.js
58 lines (50 loc) · 1.25 KB
/
multiparser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Example middleware for handling multipart forms. It should be
// "used" by an app sometime before the bodyDecoder.
//
// var Express = require('express');
// var MultiParser = require('./multiparser');
//
// var app = Express.createServer();
// app.use(MultiParser());
// app.use(Express.bodyDecoder());
var Formidable = require('formidable');
exports = module.exports = function bodyParser(opt) {
return function bodyParser(req, res, next) {
var parser = exports.parse[mime(req)];
if (parser && !req.body) {
parser(opt, req, res, next);
}
else {
next();
}
};
};
// Grab the general mime type from a request.
function mime(req) {
var str = req.headers['content-type'] || '';
return str.split(';')[0];
}
function parseMultipart(opt, req, res, next) {
var form = new Formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if (err)
next(err);
else {
req.body = extend(fields, files);
next();
}
});
}
function extend(target) {
var key, obj;
for (var i = 1, l = arguments.length; i < l; i++) {
if ((obj = arguments[i])) {
for (key in obj)
target[key] = obj[key];
}
}
return target;
}
exports.parse = {
'multipart/form-data': parseMultipart
};