Node JS Express Image Upload Rest API Example

Telegram Join Our Telegram Channel

In this tutorial, we will create very simple way rest API for Image Uploading using node js and multer. we will use express, multer, body-parser npm package for creating image upload with node.js and multer.

Now you have to follow few step to create rest api for image upload with node js. we are giving you step by step from scratch so let’s follow bellow step.

Step 1: Create Node App

run bellow command and create node app.

mkdir my-app

cd my-app

npm init

Step 2: Install express multer body-parser

Here we will install express, multer, body-parser npm package.

npm install --save express multer body-parser

Step 3: Create app.js file

app.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const multer = require('multer');
   
/*------------------------------------------
--------------------------------------------
parse application/json
--------------------------------------------
--------------------------------------------*/
app.use(bodyParser.json());
  
/*------------------------------------------
--------------------------------------------
image upload code using multer
--------------------------------------------
--------------------------------------------*/
var storage = multer.diskStorage({
   destination: function (req, file, cb) {
      cb(null, 'uploads');
   },
   filename: function (req, file, cb) {
      cb(null, Date.now() + '-' + file.originalname);
   }
});
var upload = multer({ storage: storage });
   
/**
 * Create New Item
 *
 * @return response()
 */
app.post('/api/image-upload', upload.single('image'),(req, res) => {
  const image = req.image;
    res.send(apiResponse({message: 'File uploaded successfully.', image}));
});
  
/**
 * API Response
 *
 * @return response()
 */
function apiResponse(results){
    return JSON.stringify({"status": 200, "error": null, "response": results});
}
  
/*------------------------------------------
--------------------------------------------
Server listening
--------------------------------------------
--------------------------------------------*/
app.listen(3000,() =>{
  console.log('Server started on port 3000...');
});

Run Node App:

All the required steps have been done. You must need to create “uploads” folder on root path, now you have to type the given below command and hit enter to run the Node app:

node app.js

Now, Go to your web browser, type the given URL and check it’s working:

http://localhost:3000

Image Upload API:

Method:GETURL: http://localhost:3000/api/image-upload
Telegram Join Our Telegram Channel

Leave a Reply

Your email address will not be published. Required fields are marked *

Telegram Join Our Telegram Channel

Most Viewed

Monthly Best Selling Templates

Check the latest products added to the marketplace. Fresh designs with the finest HTML5 CSS3 coding.