Upload and display images in an existing MERN app

The easiest guide to using Multer for image handling

FRONT-END

Add a property and handler for the images to the component state.

Then add a handler function to update the state. Remember to bind the function, i.e.this.onChangeImages = this.onChangeImages.bind(this), in the constructor if not using arrow functions!

File input

Multer requires multipart/form-data to work properly!

Construct a FormData() object to send the POST request and append each of the images to a property named ‘file’ (can be whatever name as long as it matches the POST route).

If you also need to send a JSON object, append it to the FormData as a String since FormData takes either String or Blob values only.

Front end is now done!

BACK-END

In your object model, define a property of type Buffer.

Install Multer by running

and include the package in your app by adding to the top of your routes file

Optional:

Add options to control and limit uploaded files.

Additional options can be found in the documentation.

Add the middleware where ‘file’ matches the key in the FormData object sent from the front-end.

Then unpack each image as a buffer, as well as any JSON object by parsing the string back into a JSON object.

Data in MongoDB
MongoDB stores buffer data as Binary objects

Now you can store images in your app!

DISPLAYING IMAGES

Once the images are retrieved from your database and loaded to your component state, convert the buffer back into images by converting it to a base64 String.

Use this function to generate the base64 encoded image data for each image path.

Boom! Done.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store