上传和设置默认 Controller 功能运行良好。然而,我们也正在尝试实现从 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。我们如何在这里包含额外的功能来删除图像?
最佳答案
有两个选项可以从 cloudinary 中删除图像:
- 通过使用管理 API。例如在 Node 中:
cloudinary.v2.api.delete_resources(['image1', 'image2'],
函数(错误,结果){console.log(结果);});
- 使用我们的上传 API:
cloudinary.v2.uploader.destroy('样本', 函数(错误,结果) {
console.log(结果,错误) });
请注意,使用我们的管理 API 是有速率限制的,您可能需要使用第二个选项。
关于node.js - 如何通过 Node.js Express 从 Cloudinary 中删除图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53942824/