【问题标题】:Updating only specific image in cloudinary node js仅更新 cloudinary 节点 js 中的特定图像
【发布时间】:2021-09-15 03:22:12
【问题描述】:

我有一个 Node Js-Express 后端和 Cloudinary 用于图像存储,用于将博客添加到数据库。我已将其配置为输入基本的博客详细信息,例如标题、类别、图像等。到目前为止,所有 CRUD 操作都运行良好。

一个博客上传了多张图片。如果用户必须对给定的博客执行更新操作,则用户可以更新数据库中的一个或多个图像。但由于图像是通过 Cloudinary 存储提供的,因此图像也需要在那里更新。我对如何将更新逻辑与 cloudinary 关联起来有点困惑。

这是我的 editBlog 控制器到目前为止的样子:

exports.editBlog = async (req, res) => {
    const { id } = req.params;
    const { title, category, content } = req.body;
    const blogImages = req.files; // There might be only single image passed to edit instead of all 3 images (for example) 

    try {
        if (!blogImages) {
            return res.status(400).json({ message: 'No images attached!' });
        }

        const updated_images = await Promise.all(blogImages.map((img) => cloudinaryUploadImage(img.path)));

        const updates = {};

        if (req.body) {
            updates.title = title;
            updates.category = category;
            updates.content = content;
            updates.images = updated_images;
        }

        const updated_data = await Blog.findOneAndUpdate(
            { _id: id },
            {
                $set: updates
            },
            {
                new: true
            }
        );

        if (!updated_data) {
            res.status(200).json({ message: 'Data does not exist' });
            return;
        }
        res.status(200).json({ message: 'Data updated', result: updated_data });
    } catch (error) {
        res.status(500).json({ message: 'Internal server error', error });
    }
};

cloudinaryUploadImage 函数:

const cloudinaryUploadImage = async image => {
  return new Promise((resolve, reject) => {
      cloudinary.uploader.upload( image , (err, res) => {
        if (err) return res.status(500).send("upload image error")
          resolve({
            img_url: res.secure_url,
            img_id: res.public_id
          }); 
        }
      ) 
  })
}

我不想用不必要的文件填满我的云存储。如果需要更换一张图片,则应从存储中删除旧图片。

如果有人能通过对这段代码进行一些调整来帮助我实现这一目标,我将不胜感激。

提前致谢

【问题讨论】:

    标签: node.js express mongoose cloudinary


    【解决方案1】:

    您在数据库中存储的内容并不明显,因此您可以在 Cloudinary 上查找图像,但如果您存储的是 img_id(这是 Cloudinary 上的公共 id),您可以使用它来覆盖原图。

    如果用户正在替换那个特定的 img_id (public_id),您可以执行另一个包含参数 public_id 的上传调用,并且您还应该传入参数 invalidate 设置为 true,以便请求使任何被替换的资产的先前版本。上传调用如下所示:

    cloudinary.uploader.upload( image , public_id: <public_id>, invalidate: true , (err, res) => { . . . }
    

    这会将 Cloudinary 上的图片替换为新图片,并将其从 CDN 的任何缓存中删除,以便您的博客获得最新版本。

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2019-04-24
      • 2017-08-24
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多