Using formidable to handle file uploads
Uploading a file to the web is a common activity, be it an image, a video, or a document. Files require different handling compared to simple POST data. Browsers embed files being uploaded into multipart messages.
Multipart messages allow multiple pieces of content to be combined into one payload. To handle multipart messages, we need to use a multipart parser.
In this recipe, we will use the formidable
module as our multipart parser to handle file uploads.
Getting ready
- First, let's create a new folder called
file-upload
and create aserver.js
file:$ mkdir file-upload $ cd file-upload $ touch server.js
- As we will be using an
npm
module for this recipe, we need to initialize our project:$ npm init --yes
- We will also need to create two subdirectories—one named
public
to store our HTML form, and another nameduploads
to store our uploaded files:$ mkdir public $ mkdir uploads