How it works...

Setting the enctype attribute of the HTML <form> element to multipart/form-data causes the browser to set the Content-Type in the request header to multipart/form-data and to embed data in any files supplied via the <input type="file"> elements into a multipart wrapper.

Our post function checks for the appropriate multipart/form-data content type in the req.headers object, rejecting the request with a 415 HTTP code (Unsupported Media Type) if the content type isn't multipart/form-data.

We create our parser by instantiating the multipart-request-stream module (mrs), passing it req.headers, and part (a function we declare shortly after).

We set up a total variable, which we use to track files from their point of discovery to when they've been completely written to disk.

The pump module is used to pipe data from the req object to the parser. This will cause our part function to be called each time the parser stream encounters a multipart boundary that contains file data.

In the part function, we check to see that the name has a non-falsey value. This is because the browser will include all file fields even if they're not populated in the multipart data. If a file section has no name, then we can simply skip it. The file argument passed to part is a stream. In the event of an empty file section, we call the resume method (a stream method) to make the stream run to completion, allowing us to process the next file section in the multipart data.

Once we've verified the section has file data, we add 1 to total.

Then we create a filename based on the HTML elements field name, the current epoch time stamp, and the original filename.

We create a write stream called dest that writes the incoming file into the uploads folder. We use pump again to pipe data from the file stream (as passed to the part function by the multipart-read-stream parser) to the dest stream.

This effectively writes a particular section of the multipart data to the uploads folder with the appropriate file. Using streams to do this means no matter how big the file is, memory and CPU usage will remain flat.

In the final parameter to the second call to pump, we provide a fat arrow callback. This will be called either in the event of an error or once all data has been written from the file stream into the dest stream. When the callback supplied to pump is called, we minus 1 from the total and write a message based on the error state to the response stream.

When the total reaches 0, we know we've processed all the files in the multipart data and can end the response with a completion message.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset