In this tutorial, we will learn how to create file upload Rest API in Node.js and Express with Multer. 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.
To create a file upload REST API in Node.js and Express with Multe we follow these steps.
Execute the following command on the terminal to create node js app:
mkdir my-app
cd my-app
npm init -y
Execute the following command on the terminal to install express and busboy dependencies:
npm install express multer body-parser --save
npm install sharp --save
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");
});
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
To upload files using rest APIs; So open postman for sending HTTP multipart/form-data
requests: as shown below picture:
In this tutorial, you have learned how to build REST API for file uploading using rest API in Node.js, Express.js and Multer.