Permalink
Browse files

backport fix for #431

  • Loading branch information...
1 parent 4e30994 commit 6c32544fbdaa2bd344398ece9364c9c7c505be87 @tj tj committed Dec 3, 2011
Showing with 26 additions and 8 deletions.
  1. +16 −5 examples/bodyParser.js
  2. +10 −3 lib/middleware/bodyParser.js
View
21 examples/bodyParser.js
@@ -3,7 +3,7 @@ var connect = require('../');
// visit form.html
-connect.createServer()
+var app = connect()
.use(connect.static(__dirname + '/public'))
.use(connect.bodyParser())
.use(function(req, res, next){
@@ -16,10 +16,21 @@ connect.createServer()
res.setHeader('Content-Type', 'text/html');
res.write('<p>thanks ' + req.body.name + '</p>');
res.write('<ul>');
- req.body.images.forEach(function(image){
+console.error(req.body);
+console.error(req.files);
+ if (Array.isArray(req.files.images)) {
+ req.files.images.forEach(function(image){
+ var kb = image.size / 1024 | 0;
+ res.write('<li>uploaded ' + image.name + ' ' + kb + 'kb</li>');
+ });
+ } else {
+ var image = req.files.images;
var kb = image.size / 1024 | 0;
res.write('<li>uploaded ' + image.name + ' ' + kb + 'kb</li>');
- });
+ }
+
res.end('</ul>');
- })
- .listen(3000);
+ });
+
+app.listen(3000);
+console.log('Server started on port 3000');
View
13 lib/middleware/bodyParser.js
@@ -144,13 +144,14 @@ exports.parse['application/json'] = function(req, options, fn){
exports.parse['multipart/form-data'] = function(req, options, fn){
var form = new formidable.IncomingForm
, data = {}
+ , files = {}
, done;
Object.keys(options).forEach(function(key){
form[key] = options[key];
});
- function ondata(name, val){
+ function ondata(name, val, data){
if (Array.isArray(data[name])) {
data[name].push(val);
} else if (data[name]) {
@@ -160,8 +161,13 @@ exports.parse['multipart/form-data'] = function(req, options, fn){
}
}
- form.on('field', ondata);
- form.on('file', ondata);
+ 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){
fn(err);
@@ -172,6 +178,7 @@ exports.parse['multipart/form-data'] = function(req, options, fn){
if (done) return;
try {
req.body = qs.parse(data);
+ req.files = qs.parse(files);
fn();
} catch (err) {
fn(err);

0 comments on commit 6c32544

Please sign in to comment.