To upload files using REST API in Node Express JS; Just create a node js app, and install multer
and express
module and then create rest API to upload files through postman with the help of Multer & express in the project.
Multer is a kind of middleman for handling multipart/form-data, which is used to send files to form or rest API.
Throughout this tutorial steps, you will learn how to create file upload REST API with Node js and Express js and also learn how to use multer in Node.js for handling multipart/form-data for uploading files.
Node.js Express Image File Upload Rest API Example with Multer and Postman
Steps to create REST API to upload files in Node JS Express using Multer & postman:
Step 1 – Create Node.js App
Simply start your cmd or terminal window and run the following commands into it to create node js application or project:
mkdir my-app cd my-app npm init -y mkdir uploads
Step 2 – Install Express and Multer Module
To install express and multer modules in project or app; Just run the following command on cmd or terminal to install it:
npm install express multer body-parser --save npm install sharp --save
Step 3 – Create Server.js File and Import Modules
Navigate to node express js project root folder and create server.js file, and then import express, multer, and path dependencies into it; like following:
var express = require("express"); var multer = require('multer'); var bodyParser = require('body-parser'); var app = express(); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, './uploads/'); }, filename: function (req, file, callback) { callback(null, file.originalname); } }); var upload = multer({ storage : storage}).single('file'); app.listen(3000,function(){ console.log("Working on port 3000"); });
Step 4 – Create Route for Rest API to Upload File
To create a file upload route using the REST API, simply create it like the following and add it to the server.js file:
app.post('/file-upload', function (req, res) { upload(req,res,function(err) { if(err) { return res.end("Error uploading file."); } res.end("File is uploaded"); }); });
Step 5 – Start Node Express Js App Server
Run the npm start on cmd or terminal window 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/file-upload
Step 6 – File Upload Rest API in Node js using Postman
Simply start your Postman application to upload files using the rest APIs in the node express js project; as shown below picture:
Conclusion
That’s it; You have learned how to create a REST API for uploading files in Node Express JS with Multer.