NewTech Lover
NewTech Lover

Reputation: 1263

How to remove images from Cloudinary by Node.js Express?

Upload and set default controller functions are working perfectly. However, we are trying to implement delete image from Cloudinary as well. How can it be done? In the documentation it was confusing. Here is the code:

 const cloudinary = require('cloudinary');
    const HttpStatus = require('http-status-codes');

    const User = require('../models/userModels');

    cloudinary.config({
      cloud_name: 'name',
      api_key: 'key',
      api_secret: 'secret'
    });

    module.exports = {
      UploadImage(req, res) {
        cloudinary.uploader.upload(req.body.image, async result => {
          await User.update(
            {
              _id: req.user._id
            },
            {
              $push: {
                images: {
                  imgId: result.public_id,
                  imgVersion: result.version
                }
              }
            }
          )
            .then(() =>
              res
                .status(HttpStatus.OK)
                .json({ message: 'Image uploaded successfully' })
            )
            .catch(err =>
              res
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .json({ message: 'Error uploading image' })
            );
        });
      },

      DeleteImage(req, res) {
    cloudinary.uploader.destroy(req.params.image, async result => {
      await User.update(
        {
          _id: req.user._id
        },
        {
          $pull: {
            images: {
              imgId: result.public_id,
              imgVersion: result.version
            }
          }
        }
      )
        .then(() =>
          res
            .status(HttpStatus.OK)
            .json({ message: 'Image deleted successfully' })
        )
        .catch(err =>
          res
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .json({ message: 'Error deleting image' })
        );
    });
  },

      async SetDefaultImage(req, res) {
        const { imgId, imgVersion } = req.params;

        await User.update(
          {
            _id: req.user._id
          },
          {
            picId: imgId,
            picVersion: imgVersion
          }
        )
          .then(() =>
            res.status(HttpStatus.OK).json({ message: 'Default image set' })
          )
          .catch(err =>
            res
              .status(HttpStatus.INTERNAL_SERVER_ERROR)
              .json({ message: 'Error occured' })
          );
      }
    };

We are using Node.js Express with Mongoose. How can we include extra function here that will remove images?

Upvotes: 4

Views: 14591

Answers (5)

jethiya007
jethiya007

Reputation: 57

I AM ADDING DIFFERENT WAYS TO DELETE CONTENT FROM CLOUDINARY WITH WORKING CODE. THERE IS A LINK TO THE DOCUMENTATION TRY GOING THROUGH IT: link

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

exports.deleteImageCloudinary = async (public_id, type = 'upload', resource_type) => {
    try {
        // invalidate: to remove cached content
        // resource_type: 'video'  //for video files
        const options = { type, invalidate: true };

        if (resource_type) {
            options.resource_type = resource_type;
        }

        return await cloudinary.uploader.destroy(public_id, options)

    } catch (err) {
        console.log('> Failed to delete Image from Cloudinary:', err.message);
        throw err;
    }
}

// deleting content based of tags: dp/ courseName
exports.deleteContentByTag = async (tag, resource_type) => {
    try {
        if (!resource_type) {
            await cloudinary.api.delete_resources_by_tag(tag)
        } else {
            await cloudinary.api.delete_resources_by_tag(tag, { resource_type: 'image' }) //doesn't require
            await cloudinary.api.delete_resources_by_tag(tag, { resource_type: 'video' })
        }
        return

    } catch (err) {
        console.log('Error deleting resources by tag: ' + err.message);
        throw err;
    }
}

// Deleting Resources in a Folder
exports.deleteFolder = async (folder) => {
    try {
        // Delete all resources within the folder
        const result = await cloudinary.api.delete_resources_by_prefix(folder);

        // Delete the empty folder
        const folderResult = await cloudinary.api.delete_folder(folder);

        return { resources: result, folder: folderResult };

    } catch (err) {
        throw err;
    }
}


// https://cloudinary.com/documentation/deleting_assets_tutorial

// Deleting Multiple Resources
// exports.deleteMany = async (files) => {
//     await cloudinary.api.delete_resources(['source'])
// }

You Can Run win this Code Import those Functions and run this file [test]

node test.js

const { deleteImageCloudinary, deleteContentByTag, deleteFolder } = require("./deleteContent");

const test = async () => {
    try {
        // Deleting a specific image
        await deleteImageCloudinary('FolderApp/[file_name]');
        console.log('Specific image deleted');

        // Deleting resources by tag
        await deleteContentByTag('dp');
        console.log('Content with tag "dp" deleted');

        // Deleting a folder's resources
        await deleteFolder('UserDP');
        console.log('Folder resources deleted');

    } catch (err) {
        console.error('Error in deletion process:', err.message);
    }
};

// Self-invoking function to automatically run the test function
(async () => {
    await test();
})();

Upvotes: -1

To remove a file or image from Cloudinary using Node.js and Express.js, you can indeed use the Cloudinary Node SDK. Here are the steps you need to follow:

npm install cloudinary

import v2

import { v2 as cloudinary } from 'cloudinary';

Configure Cloudinary with your credentials:

cloudinary.config({
  cloud_name: 'your_cloud_name',
  api_key: 'your_api_key',
  api_secret: 'your_api_secret',
});

Create a function to delete a file/image:

const deleteFile = (publicId) => {
  return new Promise((resolve, reject) => {
    cloudinary.uploader.destroy(
      publicId.trim(), // is the public_id field in the resource object
      { resource_type: 'raw' }, //tell the resource type you wanna delete (image, raw, video)
      (error, result) => {
        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      }
    );
  });
};

Upvotes: 0

Abdul Qudoos
Abdul Qudoos

Reputation: 1

const cloudinaryDeleteImg = async (fileToDelete) => {
    return new Promise((resolve) => {

        cloudinary.uploader.destroy(fileToDelete, (error, result) => {
            console.log('result :: ', result);
            resolve({
                url: result.secure_url,
                asset_id: result.asset_id,
                public_id: result.public_id,
            }, {
                resource_type: "auto",
            })
        })
    })
}

Upvotes: 0

Compty Adel
Compty Adel

Reputation: 51

it just because your req.params.image is like https:https://res.cloudinary.com/your/image/upload/v1663358932/Asset_2_bdxdsl.png

instead write your delete request like so :

cloudinary.v2.uploader.destroy('Asset_2_bdxdsl', function(error,result) {
   console.log(result, error) }) 

ps: Asset_2_bdxdsl is your image name without prefix .png !!

Upvotes: 5

Shirly Manor
Shirly Manor

Reputation: 301

There are two options to delete an image from cloudinary:

  1. By using the admin API. For example in Node:

cloudinary.v2.api.delete_resources(['image1', 'image2'], function(error, result){console.log(result);});

  1. Using our upload API:

cloudinary.v2.uploader.destroy('sample', function(error,result) { console.log(result, error) });

Please note that using our admin API is rate limited and you might want to use the second option.

Upvotes: 5

Related Questions