Create a File Upload REST API in Node.js and Express with Multer

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.

  • 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: Upload File using Node js Rest Api

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: Upload File using Node js Rest Apis

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.

#nodejs #express #multer 
 

Create a File Upload REST API in Node.js and Express with Multer
3.10 GEEK