Handling file uploads in Express using multer

First of all, download and install multer.

Include the dependency.

Initialise it into a service. The command below will initialise it with default storage type (being DiskStorage) and upload destination being the uploads/ folder.

If you don’t want the file to be saved anywhere in the file system and want to use memory storage, initialise it as follows.

You can add file size limits too. The command below sets the file upload limit to be 12 megabytes.

You can then pass around the uploadService object to other modules that use it.

To read uploads in a route, add it to the second parameter of the route definition. The following commands processes a single file uploaded under file attribute within post form-data.

The uploadedFile object here contains data about the file that was uploaded. The buffer attribute of this object contains the actual file content. The object also has other attributes like filename, mimeType and encoding that can be used to process the file according its type.

For more information, see multer on npm.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.