Building a Node.js Express REST API for Image Upload

Published on
Jigar Patel-
3 min read

Overview

building-a-nodejs-express-rest-api-for-image-upload

Introduction

In this tutorial, we'll walk through creating a straightforward REST API for uploading images using Node.js and Multer. To accomplish this, we'll utilize popular npm packages like Express, Multer, and Body-Parser.

Step 1: Setting Up Your Node.js App

Let's start by establishing the foundation for your Node.js application:

1.Begin by crafting a new directory for your project:

mkdir my-app
cd my-app

2.Initialize your Node.js app:

npm init

Step 2: Installing Dependencies

We need to install the necessary npm packages: Express, Multer, and Body-Parser.

npm install --save express multer body-parser

Step 3: Crafting the app.js File

Create a file named app.js and populate it with the following code:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const multer = require('multer');

app.use(bodyParser.json());

// Configure Multer for image upload
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 });

// Handle image upload
app.post('/api/image-upload', upload.single('image'), (req, res) => {
  const image = req.image;
  res.send(apiResponse({ message: 'File uploaded successfully.', image }));
});

// API Response utility
function apiResponse(results) {
  return JSON.stringify({ status: 200, error: null, response: results });
}

// Launch the server
app.listen(3000, () => {
  console.log('Server started on port 3000...');
});

Running the Node.js App

1. Create an "uploads" folder at the root of your project.

2. Launch the Node.js app:

node app.js

3. Open your web browser and navigate to: http://localhost:3000

Image Upload API

Method: GET URL: http://localhost:3000/api/image-upload

Output :

Image

File uploaded successfully.

save Image

Source Code

The complete source code for this tutorial is available on GitHub. You can find it Here.

About the Author

Jigar Patel is a React.js enthusiast and a software developer at JBCodeapp Company. Visit our JBCodeapp to learn more about our work in the React.js ecosystem.

We're Hiring

Are you passionate about React.js development? We're always on the lookout for talented developers to join our team. Check out our Careers Page for current job openings.

  • Building a Nodejs CRUD Application with MySQL

  • A Beginner's Guide to Learning Next.js: Step by Step

  • Node.js Folder Creation: Step-by-Step Guide for Beginners

  • How to Start a React Project in 2023

  • Understanding Web Applications: An In-Depth Look