DEV Community

Cover image for Uploading Images Using Cloudinary in Node.js
Abhishek Jaiswal
Abhishek Jaiswal

Posted on

Uploading Images Using Cloudinary in Node.js

Uploading and managing images in web applications is a common requirement, and Cloudinary is one of the most popular solutions for handling media. It offers a robust platform to store, transform, and deliver media efficiently. In this blog, we will explore how to upload images to Cloudinary using Node.js.

Prerequisites

Before we get started, make sure you have the following:

  1. Node.js installed on your system. You can download it from Node.js official website.
  2. A basic understanding of JavaScript and Node.js.
  3. A free account on Cloudinary. Sign up if you don’t already have one.

Steps to Upload Images to Cloudinary

1. Install Required Packages

Create a new Node.js project or navigate to your existing project directory and install the required npm packages:

npm init -y
npm install cloudinary multer express body-parser dotenv
Enter fullscreen mode Exit fullscreen mode
  • cloudinary: Official Cloudinary SDK for Node.js.
  • multer: Middleware for handling multipart/form-data (used for file uploads).
  • express: Web framework for building the application.
  • body-parser: Middleware for parsing incoming request bodies.
  • dotenv: Loads environment variables from a .env file.

2. Set Up Cloudinary Account

  1. Log in to your Cloudinary dashboard.
  2. Navigate to the Dashboard section, where you’ll find your Cloud name, API Key, and API Secret.
  3. Note down these credentials as we’ll need them to configure Cloudinary in our Node.js application.

3. Configure Cloudinary in Your Node.js Project

Create a .env file in the root of your project and add your Cloudinary credentials:

CLOUDINARY_CLOUD_NAME=your-cloud-name
CLOUDINARY_API_KEY=your-api-key
CLOUDINARY_API_SECRET=your-api-secret
Enter fullscreen mode Exit fullscreen mode

Next, create a config/cloudinary.js file to configure Cloudinary:

const cloudinary = require('cloudinary').v2;
const dotenv = require('dotenv');

dotenv.config();

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

module.exports = cloudinary;
Enter fullscreen mode Exit fullscreen mode

4. Set Up File Upload with Multer

Create a middlewares/multer.js file to configure Multer for file uploads:

const multer = require('multer');
const path = require('path');

// Set storage engine (temporary storage on server)
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Temporary folder for uploads
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}${path.extname(file.originalname)}`);
  },
});

// File filter to allow only images
const fileFilter = (req, file, cb) => {
  const allowedTypes = /jpeg|jpg|png|gif/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype);

  if (extname && mimetype) {
    cb(null, true);
  } else {
    cb(new Error('Only images are allowed!'));
  }
};

const upload = multer({
  storage,
  fileFilter,
});

module.exports = upload;
Enter fullscreen mode Exit fullscreen mode

5. Create Routes to Handle Image Upload

Create a simple Express application in app.js:

const express = require('express');
const bodyParser = require('body-parser');
const cloudinary = require('./config/cloudinary');
const upload = require('./middlewares/multer');
const fs = require('fs'); // For file system operations

const app = express();

// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Route to upload image
app.post('/upload', upload.single('image'), async (req, res) => {
  try {
    // Upload to Cloudinary
    const result = await cloudinary.uploader.upload(req.file.path);

    // Delete the file from the server after upload
    fs.unlinkSync(req.file.path);

    res.status(200).json({
      message: 'Image uploaded successfully!',
      url: result.secure_url,
    });
  } catch (error) {
    res.status(500).json({
      message: 'Failed to upload image',
      error: error.message,
    });
  }
});

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

6. Test the API

  1. Start your server:
   node app.js
Enter fullscreen mode Exit fullscreen mode
  1. Use a tool like Postman or cURL to test the endpoint.
  • URL: http://localhost:3000/upload
  • Method: POST
  • Body: Select form-data, and add a key image with the image file you want to upload.
  1. If everything is set up correctly, you should receive a response containing the URL of the uploaded image on Cloudinary.

Example response:

{
  "message": "Image uploaded successfully!",
  "url": "https://res.cloudinary.com/your-cloud-name/image/upload/v1234567890/your-image.jpg"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Uploading images to Cloudinary in Node.js is a straightforward process. By leveraging Cloudinary's powerful APIs and tools like Multer, you can efficiently handle image uploads, transformations, and delivery in your web applications. With the example above, you now have a solid foundation to integrate Cloudinary into your Node.js projects.


For more details, check out the official Cloudinary documentation.

Top comments (0)