How to upload image to Server using Multer in NodeJS?

Tutorial for handling images & uploading it.

·

2 min read

It’s most common required feature & yet it seems difficult to most beginners.

In this article we’re going to create REST API, which will take image as an input sends it to server.

Pre-Requisites

  • Node & Npm installed.
  • Basic Knowledge of Node JS & environment setup.
  • Postman for API testing.

Steps

  1. Setting up new express project
  2. Installing Dependencies
  3. Multer config
  4. Create Endpoint
  5. Testing API

Setting up new express project

Use express-generator for quick skeleton code.

npx express-generator upload_image

image.png

Run these commands

cd upload_image

npm i

npm start

image.png

Installing Dependencies

run this command

npm i multer nodemon

Multer => Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files

nodemon => it is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

Add nodemon into package.json file

image.png

Add Multer

Create a file multerConfig.js inside config folder

image.png

Here we’re validating image types, this will check if it matches correct type then it’ll upload image to local folder public/images otherwise it’ll throw an error.

Create Endpoint

let’s Create an Endpoint to receive image

Add this in routes/index.js

image.png

Testing Request POST localhost:3000/postImage

image.png

Conclusion

We’ve completed an endpoint which receives image in form data & stores in public/images folder.

Here’s complete code AtiaK/upload_image (github.com)

We'll be uploading images to Cloudinary in next article.

Hope this tutorial helped you!! if you need any help, you can let me know in comment section.

Thanks for reading! if you want me to cover a topic, feel free to let me know in comments below. 👇💬

☕️ You may support me by buying me a chocolate: buy me chocolate

Cheers, See you in next one. 🎉🔔

Follow me on instagram, linkedIn, medium, Github😻