如何通过Node.js Express从Cloudinary删除图像?

时间:2018-12-27 09:37:43

标签: node.js express mongoose cloudinary

上载和设置默认控制器功能正常运行。但是,我们也尝试从Cloudinary实现删除映像。怎么做到呢? 在文档中令人困惑。这是代码:

 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' })
          );
      }
    };

我们正在将Node.js Express与Mongoose结合使用。我们如何在此处包括将删除图像的额外功能?

1 个答案:

答案 0 :(得分:0)

有两种方法可以从cloudinary中删除图像:

  1. 通过使用管理API。例如在Node中:

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

  1. 使用我们的上传API:

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

请注意,使用我们的管理API是受速率限制的,您可能要使用第二个选项。