This seems like it should be a fairly simple question, but I'm having a really hard time figuring out how to approach it.
I'm using Node.js + Express to build a web application, and I find the connect BodyParser that express exposes to be very useful in most cases. However, I would like to have more granular access to multipart form-data POSTS as they come - I need to pipe the input stream to another server, and want to avoid downloading the whole file first.
Because I'm using the Express BodyParser, however, all file uploads are parsed automatically and uploaded and available using "request.files" before they ever get to any of my functions.
Is there a way for me to disable the BodyParser for multipart formdata posts without disabling it for everything else?
throw this is before app.configure
When you type
app.use(express.bodyParser())
, almost each request will go throughbodyParser
functions (which one will be executed depends onContent-Type
header).By default, there are 3 headers supported (AFAIR). You could see sources to be sure. You can (re)define handlers for
Content-Type
s with something like this:upd.
Things have changed in Express 3, so I'm sharing updated code from working project (should be
app.use
ed beforeexpress.bodyParser()
):And some pseudo-code, regarding original question:
If you need to use the functionality provided by
express.bodyParser
but you want to disable it for multipart/form-data, the trick is to not useexpress.bodyParser directly
.express.bodyParser
is a convenience method that wraps three other methods:express.json
,express.urlencoded
, andexpress.multipart
.So instead of saying
you just need to say
This gives you all the benefits of the bodyparser for most data while allowing you to handle formdata uploads independently.
Edit:
json
andurlencoded
are now no longer bundled with Express. They are provided by the separate body-parser module and you now use them as follows:Within Express 3, you can pass parameter to the
bodyParser
as{defer: true}
- which in term defers multipart processing and exposes the Formidable form object as req.form. Meaning your code can be:For more detailed formidable event handling refer to https://github.com/felixge/node-formidable
With express v4, and body-parser v1.17 and above,
You can pass a function in the
type
of bodyParser.json.body-parser will parse only those inputs where this function returns a truthy value.
In the above code,
the function returns a falsy value if the
content-type
ismultipart/form-data
.So, it does not parse the data when the
content-type
ismultipart/form-data
.I've faced similar problems in 3.1.1 and found (not so pretty IMO) solution:
to disable bodyParser for multipart/form-data:
and for parsing the content:
for example I'm using node-multiparty where the custom code should look like this: