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:
- Node & Npm installed.
- Basic Knowledge of Node JS & environment setup.
- Postman for API testing.
Steps:
- Setting up new express project
- Installing Dependencies
- Multer config
- Creating Route
- 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
Add Multer
Create a file multerConfig.js inside config folder
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
Testing
Request POST http://localhost:3000/postImage
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)