How to Upload Images to Cloudinary

Ashish SinghAshish Singh
7 min read

We are using cloudinary as it store images, video etc. on cloud and we can perform some analytics on that images or videos.

Requirement:

npm i express multer cloudinary multer-storage-cloudinary dotenv ejs

Here above we are installing following and why we are installing

  1. npm i express: Here we are installing express, so that we can create server and handle routing.

  2. npm i multer: Multer is used for file upload.

  3. npm i cloudinary: Cloudinary is used for connecting the node with Cloudinary cloud service — for uploading, deleting, transforming images/files.

  4. npm i multer-storage-cloudinary: is used for store uploaded files directly to cloudinary, instead of saving them locally. It acts as a storage engine for Multer.

  5. npm i dotenv: dotenv loads environment variables from a .env file into process.env.
    It's used in both development and production to manage secrets like API keys.

  6. npm i ejs: is used for dynamic interaction.

Create folder with any name in my case let suppose cloudinaryImageUpload, now open this folder in VSCode and open terminal in VsCode by shortcut ctrl + (tilda ` )

Now do npm init -y this will create package.json file.

Now copy code from above and install all dependencies

General setup for node

Create index.js file and copy below code

require('dotenv').config() 
const express = require('express')
const app = express()
const path = require('path')

These above line are used to import the installed packages and dotenv is required to import at top always.

MiddleWares

// middlewares
app.use(express.urlencoded({extended: false}))
app.use(express.json())

These middlewares are used for encoding form data.

Setting EJS to interact with User (frontend)

create folder with name views then run below code.

// setting ejs 
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))

Creating server

// creating server
const PORT = process.env.PORT || 5000
app.listen(PORT, ()=> console.log("Server is running"));

Now we will create front-end to get the file from user, so first in views folder create a file with name home.ejs (any name) and copy below code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
</head>
<body>
    <form action="/upload" enctype="multipart/form-data" method="post">
        <label for="file">Upload Image File</label>
        <input type="file" name="image" id="file" />
        <input type="submit" />
    </form>
</body>
</html>

Here above is ejs code on which we created a form and taking input as file and name for image is image and in form action we are redirecting /upload route and as we are using multer so we need to encrypt as multipart/form-data and method is post.

Now we see the ejs we will render this to / route so code for that add this code to your index.js file.

app.get("/", (req, res)=>{
    return res.render("home")
})

Now run the code using terminal as node filename.js so in my case node index.js it will run on localhost:5000 and now you can see the html page as follows.

Now our frontend is ready now we will see how to upload image on cloud, so code for this whole index.js is below

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

// middlewares
app.use(express.urlencoded({extended: true}));
app.use(express.json())
app.set("view engine", "ejs")
app.set("views", path.join(__dirname, "views"))

// routes
app.get("/", (req, res)=>{
    return res.render("home")
})

// server
app.listen(5000, ()=>{console.log("Server is running...")})

Now to handle backend we will create /upload route copy this below code and paste it below / route

app.post("/upload",(req, res)=>{
    return res.render("home")
})

Now the /upload route will run when we will submit any file, but till now also we are not connecting with cloudinary

Now we will create one middleware like file which handle our file helps to connect with cloudinary

Create a file with name cloudinary.js any name with .js extension now do following

  1. First to use cloudinary we have to get that package so write this line in cloudinary.js file

     const cloudinary = require("cloudinary").v2
    

    This above line is getting cloudinary version 2 code in our file and helps us to connect with cloudinary cloud using cloud name, api key & secret key.

    Now get your cloudinary account or create new account using your email or google auth, then go to cloudinary dashboard these you will see following screen

    So that is your cloud name ( they give any random string ) now to get your API key and secret click on Go to API Keys and there you will get your api key and secret key, now come to coding part.

  2. Now copy the below code and paste in cloudinary.js file and replace with your credential.

     cloudinary.config({
         cloud_name: "your-cloud-name",
         api_key: "your_api_key",
         api_secret: "your_secret_key",
     })
    

    Now as we see we are importing cloudinary to helps us to connect with cloud

  3. Now to store images, video etc. we use CloudinaryStorage from multer-storage-cloudinary this helps us to store file in cloud and in return we will get public key(url)

     const {CloudinaryStorage} = require("multer-storage-cloudinary")
     // setting up cloudinary storage
     const storage = new CloudinaryStorage({
         cloudinary: cloudinary,
         params: {
             folder: "Folder_Name",
             allowed_formats: ["jpg","jpeg", "png"],
         }
     })
    

    Now here we are creating new instance of CloudinaryStorage and store in storage variable and in object we are passing cloudinary as cloudinary so that it knows the configuration of cloudinary and in params we are having folder and in that we are passing folder-name and allowed_format in an array like ['jpg', 'jpeg', 'png'].

    Now copy below code and paste it

     const multer = require("multer")
     const upload = multer({storage})
    

    Now till here cloudinary part is done and now in multer we pass the storage information so that multer will store in it. And now we will export this upload using below code

     module.exports = upload
    
  4. Whole code of cloudinary.js

     const cloudinary = require("cloudinary").v2
     const {CloudinaryStorage} = require("multer-storage-cloudinary")
     const multer = require("multer")
    
     cloudinary.config({
         cloud_name: "your-cloud-name",
         api_key: "your_api_key",
         api_secret: "your_secret_key",
     })
    
     // setting up cloudinary storage
     const storage = new CloudinaryStorage({
         cloudinary: cloudinary,
         params: {
             folder: "Folder_Name",
             allowed_formats: ["jpg","jpeg", "png"],
         }
     })
    
     const upload = multer({storage})
     module.exports = upload
    
  5. Now in index.js in /upload route we will pass upload with file name copy below code

     const upload = require("./cloudinary")
     app.post("/upload", upload.single("image") ,(req, res)=>{
         console.log(req.file);
         return res.render("home")
     })
    

    Here first we are getting cloudinary and in /upload route we are using upload.single(“image”) here we pass the name of image which we have given in our html/ejs file while taking input from user.

    And in console.log we have req.file in that we will get the following console

     {
       fieldname: 'image',
       originalname: 'git.png',
       encoding: '7bit',
       mimetype: 'image/png',
       path: 'https://res.cloudinary.com/diyelgnkb/image/upload/v1750660626/Testing_Folder/pdm9lfvasy9ogla4vvs6.png',
       size: 68296,
       filename: 'Testing_Folder/pdm9lfvasy9ogla4vvs6'
     }
    

    As we see in console we are getting the public URL and now get the public url using req.file.path and store in db or send to frontend or to test just copy and paste the url in browser and you will see your image

  6. And to see your image in cloudinary just navigate to > Assets > Media Library > Folders and you will see you folder name , open and see your image or just Click Here to get to assets directly

Here is whole code for all three files

index.js

const express = require("express")
const app = express()
const path = require("path")
const upload = require("./cloudinary")

// middlewares
app.use(express.urlencoded({extended: true}));
app.use(express.json())

// setting up ejs
app.set("view engine", "ejs")
app.set("views", path.join(__dirname, "views"))

app.get("/", (req, res)=>{
    return res.render("home")
})

app.post("/upload", upload.single("image") ,(req, res)=>{
    console.log(req.file);
    return res.render("home")
})

app.listen(5000, ()=>{console.log("Server is running...")})

cloudinary.js

const cloudinary = require("cloudinary").v2
const {CloudinaryStorage} = require("multer-storage-cloudinary")
const multer = require("multer")

cloudinary.config({
    cloud_name: "your-cloud-name",
    api_key: "your-api-key",
    api_secret: "your-secret-api-key",
})

// setting up cloudinary storage
const storage = new CloudinaryStorage({
    cloudinary: cloudinary,
    params: {
        folder: "folder-name",
        allowed_formats: ["jpg","jpeg", "png"],

    }
})
const upload = multer({storage})
module.exports = upload

home.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
</head>
<body>
    <form action="/upload" enctype="multipart/form-data" method="post">
        <label for="file">Upload Image File</label>
        <input type="file" name="image" id="file" />
        <input type="submit" />
    </form>
</body>
</html>

Now that’s it Happy Learning.

0
Subscribe to my newsletter

Read articles from Ashish Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ashish Singh
Ashish Singh