How to use Multer to Upload Images in the MERN Stack

Mathursan Balathas
3 min readApr 12, 2022

Many of you have probably encountered a circumstance in which you needed to upload an image or another form of file to a server. This blog will show how Multer, a library, may help to store files picked from the client-side to local storage and store the file name in the database so that the file name can be used to locate the file in the local storage.

Multer

Multer is a node js middleware that 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.

Let's dig in!!

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 you can use class as well

  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

I have used axios 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 !!! 😁

--

--

Mathursan Balathas

Associate Software Engineer at Sysco LABS Sri Lanka | Undergraduate at SLIIT