File upload with Express Multer Middleware

File upload is a common functionality that is required even for the most basic applications. Even a simple website that requires user sign-up offers an option to upload profile pictures. The main feature offered by any social media website is file upload. Examples of file upload include uploading user pic, scanned documents, images, files etc to the server. But, during development receiving and handling files sent by front-end pages to the back-end can get tricky. One solution to handle file uploads with ease in an express application is multer middleware.

Multer middleware abstracts the complicated logic involved in receiving files from front-end and makes development easier.

In a node application, we can install the multer middleware with the command

npm install — save multer

This helps us handle API’s of Content-Type — multipart/form-data

Prerequisites:

Install dependencies as follows to make a basic express app

npm install — save express

npm install — save body-parser

Your package.json file should be looking like this

Uploading a single file:

Create index.js file with endpoints to upload file and to render the initial index.html as follows

Create an index.html file to be rendered as follows

Now start the server with command

node index.js

Now access our server in the address http://localhost:3000/ in any browser and choose a file to upload

On clicking upload response will be send from the server

On the server side, req.files will have the file object which can be processed as desired and req.body will contain values of the text field if any.

Uploading multiple files:

An array of files can be processed using upload array. Modify index.js as follows

Now run localhost as before

You will be able to upload multiple files.

The files uploaded are stored in a folder that we specified when we called the multer middleware.

All types of files and multipart form data can be processed with ease using multer middleware.

Leave a Reply

Your email address will not be published. Required fields are marked *

twelve + 13 =