Create Nodejs API to Upload file Using Multer

This nodejs rest api tutorial is use to upload file using multer. We will create upload rest api. This API is a post type call so that accept multipart/form-data data.The client will post data and this app will receive request and stored image into uploads folder.

We are using nodejs Multer libs. The Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.The Multer will not process any form which is not multipart (multipart/form-data).

Nodejs Upload Image Using Rest API

Lets’ create new nodejs application folder. we will add server.js file into this folder. This file is responsible for create node server and upload image into node serve.We will create HTTP Post API using nodejs http package.

Install Express, Multer and Cors Package

Let’s open node js app folder and run below command to install dependencies libs using npm.

$file-upload-nodejs> npm i express multer cors –save

The express package is use to create server, The multer is to handle upload file, CORS is used to enable cross-origin request to this server.

Create Nodejs Express Server

Lets create nodejs server using expressjs, we will import all required libs and run server into particular port.

var express = require('express')
  , path = require('path')
  , app = express()
  , multer = require('multer')
  ,cors = require('cors');
   
app.use(cors())
const PORT = process.env.PORT || 8010;
app.set('port', process.env.PORT || 8080);
app.use(express.static(path.join(__dirname, 'public')));
 app.listen(PORT, function () {
  console.log('Node.js server is running on port ' + PORT);
});

Above code, We are creating express server and run into 8010 port, now run node server.js command into command line.You can see ‘Node.js server is running on port 8010’ message into console.

Configure Nodejs Multer

We will configure multer libs and defined required params.

const DIR = 'uploads';

let storage = multer.diskStorage({
    destination: function (req, file, callback) {
      callback(null, DIR);
    },
    filename: function (req, file, cb) {
      console.log(file.originalname);
      cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

let upload = multer({storage: storage});

We have created 'uploads' folder that will have all uploaded files.The destination property will have 'upload' folder and filename will have uploaded file.The filename format would be file-1557654154573.ext.

Create Image Rest API in Nodejs

We will create HTTP Post call to store image.The image will stored into folder and send the success message to the client on successful upload.

Make the server listen on port 8010.

Run node server.js in a terminal to start this server