Image file upload using REST API in node js express example; Through this tutorial, we will learn how to upload image file in node js + express using rest APIs and multer package.
Throughout this tutorial steps, you will learn how to create file upload REST API with Node js and Express js. You will also find out how to use multer in Node.js for handling multipart/form-data for uploading files.
Node Express js Rest API File Upload with Postman & Multer
Follow the below steps to build a rest API with Node js express upload an image file using multer:
- Step 1 – Create Node Express js App
- Step 2 – Install express and Multer dependencies
- Step 3 – Create Server.js File
- Step 4 – Start Node Express Js App Server
- Step 5 – File Upload in Node js using Postman
Step 1 – Create Node Express js App
Execute the following command on the terminal to create node js app:
mkdir my-app cd my-app npm init -y
Step 2 – Install express and Multer dependencies
Execute the following command on the terminal to install express and busboy dependencies:
npm install express multer body-parser --save npm install sharp --save
Step 3 – Create Server.js File
Create server.js file and import express, multer, and path dependencies in server.js; as shown below:
var express = require("express"); var multer = require('multer'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, './uploads'); }, filename: function (req, file, callback) { callback(null, file.fieldname + '-' + Date.now()); } }); var upload = multer({ storage : storage}).single('userPhoto'); app.post('upload-avatar',function(req,res){ upload(req,res,function(err) { if(err) { return res.end("Error uploading file."); } res.end("File is uploaded"); }); }); app.listen(3000,function(){ console.log("Working on port 3000"); });
Step 4 – Start Node Express Js App Server
Execute the following command on the terminal to start the node express js server:
//run the below command npm start after run this command open your browser and hit http://127.0.0.1:3000/upload-avatar
Step 5 – File Upload in Node js using Postman
To upload files using rest APIs; So open postman for sending HTTP multipart/form-data
requests: as shown below picture:
Conclusion
Node js express rest API file upload example tutorial; you have learned how to build REST API for file uploading using rest API in Node.js, Express.js and Multer.