1 | const _ = require('lodash');
|
2 | const qs = require('qs');
|
3 | const multiparty = require('multiparty');
|
4 |
|
5 | const RE_MIME = /^(?:multipart\/.+)$/i;
|
6 | const mime = function(req) {
|
7 | let str = req.headers['content-type'] || '';
|
8 | return str.split(';')[0];
|
9 | };
|
10 |
|
11 | const format = function(obj, isFiles) {
|
12 |
|
13 | const ret = _.mapValues(obj, value => {
|
14 |
|
15 |
|
16 | if (isFiles) {
|
17 | _.each(value, v => {v.name = v.originalFilename});
|
18 | }
|
19 | return value.length === 1 ? value[0] : value;
|
20 | });
|
21 |
|
22 |
|
23 | return qs.parse(ret);
|
24 | };
|
25 |
|
26 |
|
27 | module.exports = function(req, res, next) {
|
28 | if (req.method !== 'POST' || !RE_MIME.test(mime(req))) {
|
29 | return next();
|
30 | }
|
31 | const form = new multiparty.Form();
|
32 |
|
33 | form.parse(req, function(err, fields, files) {
|
34 | req.files = format(files, true);
|
35 | req.body = format(fields);
|
36 | next();
|
37 | });
|
38 | };
|