How to upload images using Multer in the MERN stack

Arosh Segar
4 min readMay 14, 2021

Many of you might’ve come across a situation where you had to upload an image or any type of file to the server. Some of you might’ve succeeded while some of you might’ve failed. This blog will demonstrate how a library called Multer helps to store the files selected from the client side to a local storage and store the file name to the database so that file name could be used to locate the file in the local storage.

Multer

Multer is a node js middleware which helps to upload files. You have to make sure that your form is processed via multipart form data because Multer only accepts and processes multipart form data at the backend. (This will be explained with an example)

Lets get started !!! ⌨️

Folder structure

The client side implementations are done in the front-end folder and server side implementations are done in the back-end folder.

Front end

Front end folder structure

First create a react app inside the front-end folder if you haven’t created one already.

npm create-react-app .

Dependencies you’ll need : axios

I have used React Hooks but class component also works fine

  1. Import statements

2. Declaring a variable using hooks

3. Rendering the form

Note : make sure to embed the encType attribute in the form tag because multer only processes multipart form data

4. Methods to handle the inputs

5. On submit method

Axios is used to make http requests. Make sure to use form data to assign inputs and pass it to the axios method.

Back end

Back end folder structure

Dependencies you’ll need : express, cors, mongoose, multer

  1. First you need to configure the server.js file to connect to the database and also connect the routes. (I have used Mongo DB Atlas as the database and provided the connection link in a separate file and assigned it to ATLAS_URI)
server.js

2. Then you need to define the schema to describe the structure of the data to be stored in the database

user.modal.js

3. Next you need to define the route to receive the form data and store it in the database. (user.js)

import statements

defining the local storage location so that the files received from the client will be saved in the defined location.

I have used uuid to generate a unique name for the images uploaded because when the same file is uploaded more than once it will not duplicate the filename.

defining the post route method

upload.single(‘photo’) accepts the photo and stores it in request.file object. The filename will be stored in the database and not the whole file. The file will be saved in the local storage in the folder called ‘images’. The file could be accessed by the filename stored in the database.

Hope this works for you !!! 😁

--

--

Arosh Segar

An undergraduate studying for a Bachelor's degree in Information Technology and Specializing in Software Engineering