Recently I had a task of uploading an image to my cloud storage using Express. I knew I had to use multipart parameter for the file but I also had to pass a security token to make sure the request came from an authorized source. I went with the connect-busboy library. I implemented the solution to read both file and text parameters and in this tutorial I will show you how.
1. Setup a post method
First set up a post method using Express and add the busboy middleware to the method. I’m adding the middleware specifically to the method because I’m only using busboy to handle file upload requests for any other requests I use
immediate: true makes sure that the parsing begins immediately on the request.
2. Parse request parameters
To read form parameters we use
req.busboy.on() method. The method accepts 2 parameters:
- The name of the event triggered by parsing the parameters
- The callback function when the event is triggered
First we add a way to read the
file type parameters:
Whenever busboy parses parameter of type
file we check for the
data value and if it’s not
null we concatenate it in into the existing
fileData buffer variable. This is done for files that are too big to get parsed all at once.
Since I’m only passing one parameter of type
file I have no need to check for
fieldName. If you have multiple files passed then you should check
fieldName to make sure you’re assigning
data to the correct buffer.
Next we implement a way to read the security token as a text field parameter:
Here it’s pretty straightforward — busboy parses
field type parameter and we check the
fieldName value to make sure it’s our token
Finally we implement our
This method lets us know that busboy is finished parsing all the parameters. Make sure to put all the code that you plan on executing after the parameters are done parsing here. Otherwise you might have files that are not fully parsed.
And that’s pretty much everything you should need to parse multiple parameters using busboy. Here’s the full method for you:
Hope this post was helpful. Thank you!