BlogPost

August 26, 2024

How to Upload Images to Cloudinary Using Node.js: A Comprehensive Guide

In modern web development, handling media files like images and videos is a common requirement. Storing these files directly on your server can lead to storage and performance issues. To overcome this, cloud-based media storage solutions like Cloudinary offer a robust way to manage, store, and serve media files efficiently. In this blog, we will walk you through the process of uploading images to Cloudinary using Node.js.

 

What is Cloudinary?

Cloudinary is a cloud service that provides an end-to-end image and video management solution. It allows developers to easily upload, store, manage, manipulate, and serve images and videos across the web and mobile applications.

 

Prerequisites

Before we dive into the code, make sure you have the following:

  • A Cloudinary account (you can sign up for free).
  • Node.js installed on your machine.
  • Basic knowledge of JavaScript and Node.js.

 

Step 1: Setting Up the Node.js Project

 

First, let’s create a new Node.js project. Open your terminal and run the following commands:

 

mkdir cloudinary-upload
cd cloudinary-upload
npm init -y

 

This will create a new directory and initialize a Node.js project with a package.json file.

 

Step 2: Install Required Packages

Next, we need to install the necessary packages:

  • dotenv: To manage environment variables.
  • cloudinary: The official Cloudinary Node.js SDK.
  • express: A minimal web framework for Node.js (optional, but used here for demonstration).

 

npm i cloudinary dotenv express express-fileupload mongoose

 

Step 3: Configure Cloudinary

 

CLOUD_NAME=your_cloud_name
API_KEY=your_api_key
API_SECRET=your_api_secret

 

Step 4: Set Up Cloudinary in Node.js

Now, create a new folder called config  and create file cloudinary.js and add the following code:

 

 

const cloudinary = require('cloudinary').v2

exports.cloudinaryConnect = () =>{
        try {
             cloudinary.config({
                cloud_name:process.env.CLOUD_NAME,
                api_key: process.env.API_KEY,
                api_secret: process.env.API_SECRET,
             })
        } catch (error) {
            console.log(error);
        }
}

 

Step 5: Set Up Database Connection in Node.js

 

Now,  create file database.js  in  config  folder and add the following code:

 

const mongoose = require("mongoose");

require("dotenv").config();

exports.connect = () => {
    mongoose.connect(process.env.MONGODB_URL, {
        useNewUrlParser:true,
        useUnifiedTopology:true
    })
    .then(() => {console.log("DB connected successfully")})
    .catch( (err) => {
        console.log("DB CONNECTION ISSUES");
        console.error(err);
        process.exit(1);
    } );
}

 

 

Step 6: Write a cloudinary function to upload files in Node.js

 

Now,  create a folder controllers and create file fileUpload.js  and add the following code:

 

const cloudinary = require("cloudinary").v2;
const File = require("../models/File");

function isFileTypeSupported(type, supportedTypes) {
  return supportedTypes.includes(type);
}

async function uploadFileToCloudinary(file, folder, quality) {
  const options = { folder };
  if(quality){
    options.quality = quality;
  }
  options.resource_type = "auto";
  return await cloudinary.uploader.upload(file.tempFilePath, options);

}



exports.imageUpload = async (req, res) => {
  try {
    //data fetch
    const { name, email, tags } = req.body;
    const file = req.files.file;

    const supportedTypes = ["jpg", "jpeg", "png"];
    const fileType = file.name.split(".")[1].toLowerCase();
    if (!isFileTypeSupported(fileType, supportedTypes)) {
      return res.status(400).json({
        success: false,
        message: "file format not supported",
      });
    }
    const response = await uploadFileToCloudinary(file, "CoddingWallah");

    //database intraction

    const fileData = await File.create({
      name,
      tags,
      email,
      imageUrl: response.secure_url,
    });

    res.json({
      success: true,
      message: "Image Succesfully Uploaded",
    });
  } catch (error) {
    console.log(error);
  }
};

exports.videoUpload = async (req, res) => {
  try {
    //data fetch
    const { name, email, tags } = req.body;
    const file = req.files.file;

    const supportedTypes = ["mp4", "mov"];
    const fileType = file.name.split(".")[1].toLowerCase();
    if (!isFileTypeSupported(fileType, supportedTypes)) {
      return res.status(400).json({
        success: false,
        message: "file format not supported",
      });
    }

    const response = await uploadFileToCloudinary(file, "CoddingWallah");

    //database intraction
    const fileData = await File.create({
      name,
      tags,
      email,
      imageUrl: response.secure_url,
    });

    res.json({
      success: true,
      message: "Image Succesfully Uploaded",
    });
  } catch (error) {
    console.log(error);
    res.status(400).json({
      success: false,
      message: "something wrong",
    });
  }
};

//imagr reducer

exports.imageReducerUpload = async (req, res) => {
  try {
    const { name, email, tags } = req.body;
    const file = req.files.file;

    const supportedTypes = ["jpg", "jpeg", "png"];
    const fileType = file.name.split(".")[1].toLowerCase();
    if (!isFileTypeSupported(fileType, supportedTypes)) {
      return res.status(400).json({
        success: false,
        message: "file format not supported",
      });
    }
    const response = await uploadFileToCloudinary(file, "CoddingWallah",30);

    //database intraction

    const fileData = await File.create({
      name,
      tags,
      email,
      imageUrl: response.secure_url,
    });

    res.json({
      success: true,
      message: "Image Succesfully Uploaded",
    });
  } catch (error) {
    console.log(error);
    res.status(400).json({
      success: false,
      message: "something wrong",
    });
  }
};

 

 

Step 7: Set Up Model  in Node.js

 

Now,  create a folder models and create file File.js  and add the following code:

 

const mongoose = require('mongoose');
const fileSchema = new mongoose.Schema({
    name:{
        type:String,
        required:true,
    },
    imageUrl:{
        type:String,
    },
    tags:{
        type:String,
    },
    email:{
        type:String,
        required:true,
    }
});

const File = mongoose.model("File",fileSchema);
module.exports = File;

 

Step 8: Set Up Routes  in Node.js

 

Now,  create a folder routes and create file FileUpload.js  and add the following code

 

 

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

const { imageUpload, videoUpload, imageReducerUpload} = require('../controllers/fileUpload');


router.post('/imageupload',imageUpload);
router.post('/videoupload',videoUpload);
router.post('/imagereducerupload',imageReducerUpload);


module.exports = router;

 

Step 9: Set Up Entry point  in Node.js

 

create index.js in root directory

 

const express = require("express");
const app = express();

require("dotenv").config();

const PORT = process.env.PORT || 4000;

app.use(express.json());

const fileupload = require('express-fileupload');
app.use(fileupload({
    useTempFiles : true,
    tempFileDir : '/tmp/'
}));
const db = require('./config/database');
db.connect();

const cloudinary = require('./config/cloudinary');
cloudinary.cloudinaryConnect();

const upload = require('./routes/FileUpload');
app.use('/api/v1/upload',upload);

app.listen(PORT,()=>{
    console.log(`app is on ${PORT}`)
})
©CodingWallah. All Rights Reserved by CodingWallah