How to upload image to Server using multer in NodeJS?

Atia Z
3 min readOct 7, 2022

--

Here’s tutorial for handling images & uploading it.

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 Req:

  1. Node & Npm installed.
  2. Basic Knowledge of Node JS & environment setup.
  3. Postman for API testing.

Steps:

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

Setting up new express project

Use express-generator for quick skeleton code.

npx express-generator upload_image

after this then run

cd upload_image

npm i

npm start

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

package.json

Add Multer

Create a file multerConfig.js inside config folder

multerConfig.

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.

Finally let’s Create an Endpoint to receive image

Add this in routes/index.js

index.js

Testing

Request POST http://localhost:3000/postImage

postman

Here you can see image is saved to server.

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)

Did you find it helpful?

Let me know if you found this helpful or need any help.

Subscribe here to be on my email list to be notified for my new exciting blogs.

Cheers, See you in next one.

Follow me on instagram, github, linkedIn

--

--