Skip to content

Instantly share code, notes, and snippets.

@jxson
Forked from weaver/.gitignore
Created October 1, 2011 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jxson/1256797 to your computer and use it in GitHub Desktop.
Save jxson/1256797 to your computer and use it in GitHub Desktop.
Express + Formidable, works with bodyParser and sets req.body correctly.
node_modules
var Express = require('express'),
Form = require('connect-form'),
Upload = require('./upload'),
app = Express.createServer();
app.use(Express.logger());
app.use(Express.bodyParser());
app.use(Form());
app.use(Express.static(__dirname));
app.post('/upload', Upload.wait, function(req, res) {
res.send(req.body, 200);
});
app.listen(4000);
console.log('http://localhost:4000/index.html');
<form method="post" action="/upload" enctype="multipart/form-data">
<p>Title: <input type="text" name="title" /></p>
<p>File: <input type="file" name="upload" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
{
"name": "express-form-example",
"main": "./app.js",
"dependencies": {
"express": ">=1.0.0",
"connect-form": ">=0.2.1"
}
}
exports.wait = wait;
function wait(req, res, next) {
if (!req.form)
next();
else
req.form.complete(function(err, fields, files) {
if (err)
next(err);
else {
req.fields = fields;
req.files = files;
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment