Node Js Express Image Upload Rest API Tutorial

Node image upload rest api example; Image uploading is a crucial functionality in almost every web and mobile application.

If you are just getting started or a newbie developer, things might get cumbersome for you in the Node environment.

This tutorial is going to show you the right path for building node image uploading REST API using express js, Cross-Origin Resource Sharing (CORS), and multer modules.

The primary purpose of this article to teach you how to create file upload functionality in node js using express and multer.

Express is a powerful Node.js web application framework that gives great set of features for web and mobile applications.

Whereas, Multer is used in node js, it is a middleware for handling multipart/form-data, which is mainly used for uploading image files.

You will be taught to use multer with express js for building node image upload REST API from absolute scratch.

How to Build Multiple Image Upload REST API in Node

  • Step 1: Build Node Project
  • Step 2: Install Node Modules
  • Step 3: Set Up Middleware
  • Step 4: Make Image Controller
  • Step 5: Build REST API Routes
  • Step 6: Create Node Server
  • Step 7: Test Multi Image Upload API

Build Node Project

For setting up a node app, create a blank new folder.

mkdir node-demo

Next, step inside the app directory.

cd node-demo

Now, you have to type the following command to generate the package.json file.

npm init

Make sure to create the app.js file in your node project root. After creating the file, ensure that you added it inside the package.json file.

{
  "main": "app.js",
}

In order to store the image files, you need a directory. Create a ‘public’ directory and ‘uploads’ the directory within the public folder.

Install Node Modules

We need some modules such as express, multer and cors.

npm install express multer cors

Set Up Middleware

To build the image upload REST API, we need a middleware create the ‘middleware’ folder and imgUpload.js file.

After that add the given code into the middleware/imgUpload.js file.

const util = require('util')
const multer = require('multer')

const DIR = './public/uploads/'

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR)
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-')
    cb(null, fileName)
  },
})

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == 'image/png' ||
      file.mimetype == 'image/jpg' ||
      file.mimetype == 'image/jpeg'
    ) {
      cb(null, true)
    } else {
      cb(null, false)
      return cb(new Error('Image type should be: .jpeg, .jpg and .png!'))
    }
  },
}).single('file')

let imgUploadMiddleware = util.promisify(upload)

module.exports = imgUploadMiddleware

Make Image Controller

Now, we are going to create a image controller therefore create controller folder, inside this folder create img.controller.js also insert the given code into the controller file.

const upload = require('../middleware/imgUpload')

const uploadFile = async (req, res) => {
  try {
    await upload(req, res)

    if (req.file == undefined) {
      return res.status(400).send({ message: 'Select image to upload' })
    }

    res.status(200).send({
      message: 'Image successfully uploaded: ' + req.file.originalname,
    })
  } catch (err) {
    console.log(err)

    if (err.code == 'LIMIT_FILE_SIZE') {
      return res.status(500).send({
        message: 'File size should be less than 5MB',
      })
    }

    res.status(500).send({
      message: `Error: ${err}`,
    })
  }
}

module.exports = { uploadFile }

Build REST API Routes

Next, you are going to create a routes directory, in this folder create img-upload.route.js file and insert the given code into it.

const express = require('express')
const router = express.Router()

const controller = require('../controller/img.controller')

const routes = (app) => {
  router.post('/img-upload', controller.uploadFile)
  app.use(router)
}

module.exports = routes

Create Node Server

At the root of the node, the project create an app.js file; in this file, we will add code to set up the node server.

Make sure to add the given code to the app.js file.

const express = require('express')
const cors = require('cors')
const app = express()

global.__basedir = __dirname

var _cors = {
  origin: 'http://localhost:4000',
}

app.use(cors(_cors))

const _appRoutes = require('./routes/img-upload.route')

app.use(
  express.urlencoded({
    extended: true,
  }),
)

_appRoutes(app)

const port = process.env.PORT || 4000
app.listen(port, () => {
  console.log('App working on: ' + port)
})

app.use((req, res, next) => {
  setImmediate(() => {
    next(new Error('Server error'))
  })
})

app.use(function (err, req, res, next) {
  console.error(err.message)
  if (!err.statusCode) err.statusCode = 500
  res.status(err.statusCode).send(err.message)
})

Test Image Upload REST API

You have to now start the node server using the given code.

node app.js

To test the file upload api we need to download and run the Postman app.

After that, use the given api for file uploading.

If the validation criteria don’t match, it will throw an error

HTTP Method API
POST http://localhost:4000/img-upload

We have added the validation to image upload REST API; only 5MB size of image is allowed with .png, jpg, and jpeg format.

Node Js Express Image Upload Rest API Tutorial

Summary

In this detailed guide, we described how to create image file uploading REST API in Node js application, not just that we also learned how to use multer in express js for building file upload rest api.