Handling 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. The file uploads in this recipe will be stored on disk.
Getting ready
To get started, let’s set up the foundation for our file upload recipe.
- 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 a
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...