A Beginner friendly guide to Image upload to Cloudinary with Multer in Node.js

A Beginner friendly guide to Image upload to Cloudinary with Multer in Node.js

As a developer, you often have to manage images. Tasks such as uploading images, compressing images, and displaying images are common challenges you face during development.

In today’s article let's have a look at how to handle images efficiently with the help of Cloudinary, a robust cloud-based media management platform, that can be used to manipulate our images easily.

Cloudinary is a service Trusted by 1.5 million developers It provides lot of features transform and customize images. Including AI capabilities.

Why Not Local Disk ?

You might wonder why we need a service like Cloudinary. Why can't we just save our images on the server's local disk instead?

Cloudinary provide following features which take to of time to implement if we use server disk as storage.

  • Cloudinary can be used to optimizes media and there are various transformations like resizing, cropping, and applying filters provided.
  • Cloudinary delivers your media assets through a high-performance Content Delivery Network (CDN), ensuring fast and reliable access for your users.
  • Allows you to search your media and also Cloudinary automatically backs up media and keeps track of revisions, which can be revert later if needed.

In addition to these core features, Cloudinary's free plan also includes access to some free add-ons that can extend its functionality, like Background Removal and Content Analysis and Auto-Tagging.

Now I hope you get an idea, what are the benefit of using service like Cloudinary. Now Let's have a look how to implement a solution with Cloudinary, With the help of 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. - multer

Prerequisites:

If you would like to follow this tutorial, make sure you have the following installed:

  1. Node.js installed on your computer
  2. Cloudinary account (Sign up here)

Step 1: Set up your Node.js Express project

First let's create some basic Nodejs project with the help of Express.js. You can also use other web frameworks as well.

💡
Read about Top 100 npm packages Article for more frameworks.

Initialize the project using following command. which create package.json file for you.

npm init -y 

Then install the necessory dependencies using following commands

npm install express multer cloudinary
  • Expressjs : web framework to handle request
  • Multer : middleware for handling images
  • Cloudinay : A library that help us to interact with cloudinary API endpoints easily.

Step 2: Obtain Cloudinary Keys

I hope that now you have created a cloudinary account and if not go to cloudinary.com and create your account.

After create your account you need to retrieve your API Key, API Secret, and Cloud Name. you can find those keys in dashboard.

consider following screenshot for more details.

cloudinary dashboard
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

Step 3: Set up Multer for image uploads.

Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It makes the process of file handling in applications seamless and straightforward.

Create a multer-config.js file to configure Multer:

// multer-config.js

const multer = require('multer')
const storage = multer.memoryStorage()  // store image in memory
const upload = multer({storage:storage})

module.exports = upload

Step 4: Implement Express route for image upload

In your app.js or index.js, set up the Express route to handle image uploads:

// app.js or index.js
const express = require('express');
const cloudinary = require('cloudinary').v2;
const upload = require('./multer-config');
const app = express();

// Cloudinary configuration
cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});

// Express route for image upload
app.post('/upload', upload.single('image'), async (req, res) => {
  try {
    // Upload image to Cloudinary
    const result = await cloudinary.uploader.upload(req.file.path , {
       folder:'folder_name'
    });

    // Send the Cloudinary URL in the response
    res.json({ imageUrl: result.secure_url });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Error uploading image to Cloudinary' });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

In above Node.js code that uses Express and Cloudinary to upload an image to a Cloudinary account and get the URL of the uploaded image.

First, the express and cloudinary modules are imported. The code uses a file upload middleware module called multer-config to handle the file upload.

AnExpress route /upload is created to handle the file upload. This route accepts a single file named image and uploads it to Cloudinary using the cloudinary.uploader.upload() method. The image is uploaded to a specific folder within Cloudinary named folder_name.

After the upload, the server responds to the request with a JSON object containing the URL for the uploaded image.

Finally, the server is started on a port configured by the environment variable PORT or defaults to port 3000. When the server starts running, it logs a message to the console.

Step 5: Test the image upload endpoint

Now you have an up and running end point to upload images to Cloudinary using Nodej with the help of multer.

Run your Node.js application and use a tool like Postman to test the image upload endpoint (POST /upload). Attach an image file with the key image, and you should receive a JSON response with the Cloudinary URL.

Congratulations! You’ve successfully set up a Node.js Express application with Multer for image uploads to Cloudinary.

In upcomming articles let's talk about how to manipulate our images easily. Feel free to improve this according to your use case and read their documentation.