我是新使用cloudinary服务。 在cloudinary上成功上传图片并获取公共URL。 但我想用新镜像更新现有镜像,cloudinary 上有没有选项可以更新现有镜像? 请在这方面建议我。 预先感谢:)
是的,可以更新已上传到 Cloudinary 的资产。
为此,您需要执行 upload() 方法调用并提供要上传的新资源(在
file
参数中),并将 public_id
参数设置为您现有的 public_id
想要覆盖。作为 overwrite
方法一部分的 upload()
参数已默认为 True
,这将是用新资产替换帐户中的旧资产所需的全部内容。您还应该考虑将 invalidate
参数设置为 True
,以告诉 Cloudinary 清除旧资产的 CDN 缓存,以便现有 URL 在更新后返回新资产。
除了 API 之外,您还可以通过媒体库 UI 上传覆盖图像。为此,您需要转到媒体库并使用“上传”按钮启动“上传小部件”。您将在底部看到一个“高级”选项,允许您指定一个
public_id
,将其设置为要覆盖的 public_id,然后只需拖放或选择要上传的资产即可。在上传完成之前,您将收到确认覆盖操作的提示。
使用 upload() 函数更新现有图像或文件时存在缓存:
如果您提供的错误a
在您的云端存储中不存在,则上传方法将创建一个新文件,其中包含错误的[不存在的public_id]public_id
。public_id
因此,要更新现有文件,我希望首先借助 destroy() 销毁该文件,然后再次上传。
注意: distroy 函数总是解析如果找不到文件则返回
{ result: 'not found' }
否则如果成功删除文件则返回 { result: 'ok' }
。
第1步.借助public_id销毁镜像
const { result } = await cloudinary.v2.uploader.destroy(public_id);
if (result === "not found")
throw new BadRequestError("Please provide correct public_id");
if (result !== "ok")
throw new Error("Try again later.");
});
第2步.重新上传。
const myCloud = await cloudinary.v2.uploader.upload(avatar.url, {
public_id: avatar.public_id,
});
console.log(myCloud);
如果有人知道其他更好的解决方案,请分享!!
谢谢你
const imageUpdater = async (imagePublicId, imagePath) => {
try {
const result = await cloudinary.uploader.upload(imagePath, {
public_id: imagePublicId,
})
return result
} catch (error) {
throw new AppError(
StatusCodes.BAD_REQUEST,
"Cannot update image. Please try again."
)
}
}