Handling file uploads
We cannot process an uploaded file in the same way process other POST data. When a file input is submitted in a form, the browser embeds the file(s) into a multipart message.
Multipart was originally developed as an email format, allowing multiple pieces of mixed content to be combined into one payload. If we attempted to receive the upload as a stream and write it to a file, we would have a file filled with multipart data instead of the file or files themselves.
We need a multipart parser, the writing of which is more than a recipe can cover. So we'll be using the multipart-read-stream
module, which sits on top of the well-established busboy
module, to convert each piece of the multipart data into an independent stream, which we'll then pipe to disk.
Getting ready
Let's create a new folder called uploading-a-file
and create a server.js
file and an uploads
directory inside that:
$ mkdir uploading-a-file $ cd uploading-a-file $ touch server.js $ mkdir uploads
We'll also...