NodeJS 从Cloudinary URL提取公共ID

y53ybaqx  于 2023-05-17  发布在  Node.js
关注(0)|答案(4)|浏览(204)

我正在使用Cloudinary将我的NodeJS项目的媒体托管在云上。要从Clodinary Cloud中删除一个镜像,我需要将该镜像的Public Id传递给Cloudinary API。我意识到,公共ID嵌入到URL中,如何从URL中提取出来

因为,我不想以这种格式存储数据:

  1. image : {
  2. url : `http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png`,
  3. publicId : `rsorl4rtziefw46fllvh`
  4. }

相反,我发现最好这样存储它:

  1. image : `http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png`
htrmnn0y

htrmnn0y1#

这个问题的解决方案是实现一个函数,该函数提取作为参数传入的每个URL的publicId。
函数如下:

  1. const getPublicId = (imageURL) => imageURL.split("/").pop().split(".")[0];

@ loic-vdb建议后编辑 *
说明

1.它使用“/”作为分隔符将字符串拆分为数组。
imageURL=”http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png“;
变成

  1. imageURL = [ 'http:',
  2. '',
  3. 'res.cloudinary.com',
  4. 'cloud_name',
  5. 'image',
  6. 'upload',
  7. 'v1647610701',
  8. 'rsorl4rtziefw46fllvh.png' ]

1.接下来,弹出数组(返回数组的最后一个元素)
imageURL = 'rsorl4rtziefw46fllvh.png';
1.现在,使用“.”作为分隔符将此字符串拆分为数组,我们得到:
imageURL = [ 'rsorl4rtziefw46fllvh','png' ]
1.最后选择第0个元素,它是我们的PublicId返回值,
imageURL = 'rsorl4rtziefw46fllvh';

展开查看全部
kr98yfug

kr98yfug2#

也可以使用cloudinary-build-url包中的extractPublicId方法

  1. import { extractPublicId } from 'cloudinary-build-url'
  2. const publicId = extractPublicId(
  3. "http://res.cloudinary.com/demo/image/upload/v1312461204/sample.jpg"
  4. )

文件:https://cloudinary-build-url.netlify.app/usage/extractPublicId

k2fxgqgv

k2fxgqgv3#

基于the answer by a Cloudinary support team member
... public_id包含所有文件夹,public_id的最后一部分是文件名。
以下是我尝试和工作

  1. const path = require("path");
  2. const getPublicId = (imageURL) => {
  3. const [, publicIdWithExtensionName] = imageURL.split("upload/");
  4. const extensionName = path.extname(publicIdWithExtensionName)
  5. const publicId = publicIdWithExtensionName.replace(extensionName, "")
  6. return publicId
  7. };

尤其是在将资产存储在文件夹中的情况下

ds97pgxw

ds97pgxw4#

来自@Aditya Pandey的答案在我的情况下不起作用,因为我的文件名中有句点字符,所以我不得不修改代码:

  1. const extractPublicId = (link: string) => {
  2. const dottedParts = link.split('/').pop()!.split('.');
  3. dottedParts.pop();
  4. return dottedParts.join('.');
  5. };

此代码提取从最后一个/到最后一个.字符的部分。如果不使用Typescript,则在pop()之后不需要!

相关问题