multipart.js
2.98 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*!
* Connect - multipart
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var formidable = require('formidable')
, _limit = require('./limit')
, utils = require('../utils')
, qs = require('qs');
/**
* noop middleware.
*/
function noop(req, res, next) {
next();
}
/**
* Multipart:
*
* Parse multipart/form-data request bodies,
* providing the parsed object as `req.body`
* and `req.files`.
*
* Configuration:
*
* The options passed are merged with [formidable](https://github.com/felixge/node-formidable)'s
* `IncomingForm` object, allowing you to configure the upload directory,
* size limits, etc. For example if you wish to change the upload dir do the following.
*
* app.use(connect.multipart({ uploadDir: path }));
*
* Options:
*
* - `limit` byte limit defaulting to none
* - `defer` defers processing and exposes the Formidable form object as `req.form`.
* `next()` is called without waiting for the form's "end" event.
* This option is useful if you need to bind to the "progress" event, for example.
*
* @param {Object} options
* @return {Function}
* @api public
*/
exports = module.exports = function(options){
options = options || {};
var limit = options.limit
? _limit(options.limit)
: noop;
return function multipart(req, res, next) {
if (req._body) return next();
req.body = req.body || {};
req.files = req.files || {};
if (!utils.hasBody(req)) return next();
// ignore GET
if ('GET' == req.method || 'HEAD' == req.method) return next();
// check Content-Type
if ('multipart/form-data' != utils.mime(req)) return next();
// flag as parsed
req._body = true;
// parse
limit(req, res, function(err){
if (err) return next(err);
var form = new formidable.IncomingForm
, data = {}
, files = {}
, done;
Object.keys(options).forEach(function(key){
form[key] = options[key];
});
function ondata(name, val, data){
if (Array.isArray(data[name])) {
data[name].push(val);
} else if (data[name]) {
data[name] = [data[name], val];
} else {
data[name] = val;
}
}
form.on('field', function(name, val){
ondata(name, val, data);
});
form.on('file', function(name, val){
ondata(name, val, files);
});
form.on('error', function(err){
if (!options.defer) {
err.status = 400;
next(err);
}
done = true;
});
form.on('end', function(){
if (done) return;
try {
req.body = qs.parse(data);
req.files = qs.parse(files);
} catch (err) {
form.emit('error', err);
return;
}
if (!options.defer) next();
});
form.parse(req);
if (options.defer) {
req.form = form;
next();
}
});
}
};