Node js Express Rest API Image Upload Example

Nodejs express rest apis for image file upload example; In this tutorial, i am going to show you how to upload image file in node js express using rest apis with multer library.

Multer is a middleware for handling multipart/form-data, extremely useful for managing file uploads. You can use Express. js middleware framework to build the single or multiple file upload system along with Multer and Node. js.

In node js rest api file upload with multer package tutorial; you will learn how to create rest api in node js express app for image file upload and how to use this apis with postman app and other apps.

Image Upload using Rest Api in Node.js Express with Multer

  • Step 1 – Create New Node Js Application
  • Step 2 – Install Express , Body parse, cors and Multer Library
  • Step 3 – Create index.js file
  • Step 4 – Run Node js Express Image File Upload App
  • Step 5 – Upload Image By Calling Node js Rest Api on Postman

Step 1 – Create New Node Js Application

Open your command prompt and execute the following command on it to create a new node js application:

mkdir my-app
cd my-app
npm init

Step 2 – Install Express , Body parser, cors and Multer Library

Install express, body parser, cors and multer library into your node js express application by executing the following command on command prompt:

npm install express body-parser cors multer --save
  • Express  – Node.js Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
  • body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.
  • cors – It’s an Express middleware for enabling Cross-Origin Resource Sharing requests. Just because of it, We can access the API in different applications.
  • multer – 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.

Step 3 – Create index.js file and Import Libraries

Create index.js and import the above installed libararies. So visit your app root directory and create route for showing image upload and store image into directory, as shown below:

var express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const multer = require('multer')
 
var app = express();
var port = process.env.PORT || 4000;
 
// enable CORS
app.use(cors());

// parse application/json
app.use(bodyParser.json());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}));

// serving static files
app.use('/uploads', express.static('uploads'));
 
// request handlers
app.get('/', (req, res) => {
    res.send('Node js file upload rest apis');
});

// handle storage using multer
var storage = multer.diskStorage({
   destination: function (req, file, cb) {
      cb(null, 'uploads');
   },
   filename: function (req, file, cb) {
      cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
   }
});

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

// handle single file upload
app.post('/upload-file', upload.single('dataFile'), (req, res, next) => {
   const file = req.file;
   if (!file) {
      return res.status(400).send({ message: 'Please upload a file.' });
   }
   return res.send({ message: 'File uploaded successfully.', file });
});

app.listen(port, () => {
    console.log('Server started on: ' + port);
});

The following multer package code will store images into directory. So the next step should be the create folder as “uploads” in the root directory where all our files will be saved.

// handle storage using multer
var storage = multer.diskStorage({
   destination: function (req, file, cb) {
      cb(null, 'uploads');
   },
   filename: function (req, file, cb) {
      cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
   }
});

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

The following routes will be handle the single uploaded file request:

// handle single file upload
app.post('/uploadfile', upload.single('dataFile'), (req, res, next) => {
   const file = req.file;
   if (!file) {
      return res.status(400).send({ message: 'Please upload a file.' });
   }
   return res.send({ message: 'File uploaded successfully.', file });
});

Step 4 – Run Node js Express File Upload App

Open your command prompt and execute the following command to run node js express file upload application:

//run the below command

node index.js

Step 5 – Upload Image By Calling Node js Rest Api on Postman

Open your postman app and call node js express rest api to upload image file; you can see on the following image how to call node js express image upload rest api in postman app:

Conclusion

Nodejs express rest apis for image file upload example; You have learned how to upload image file in node js express using rest apis with multer library.

Be First to Comment

Leave a Reply

Your email address will not be published.