使用Node.js SDK从Cloudinary获取文件元数据。

huangapple go评论63阅读模式
英文:

Fetch file metadata from cloudinary using Node.js SDK

问题

我正在使用React构建一个网站,并将我的图像资产存储在Cloudinary服务器上。我想创建一个滚动图库,其中包括图像和描述。

示例:

// STATE

const [cloudImgData, fetchData] = useState([
{url: ['url string', ..], meta: ['metadata string']},
{url: ['url string', ..], meta: ['metadata string']},
...
])

const fetchIMGS = () => {
  //...fetch images
} 

return (
<div className="image_gallery">
  {cloudImgData.map((img) => {
    return (
      <img src={img.url} alt="Image Description"/>
      <p>{img.meta}</p>
    )
  })}
</div>
)

对于后端,我一直在使用Node.js SDK及其方法,我正在使用Admin和Metadata API。

const cloudinary = require('cloudinary').v2;
require('dotenv').config();

const getGalleryFromCloudinary = async (exhibit) => {
 
  try {

    const options = { 
      cloud_name: process.env.CLOUD_NAME,
      api_key: process.env.CLOUD_API,
      api_secret: process.env.CLOUD_SECRET_API,
      secure: true
    };

    cloudinary.config(options);

    // 获取URL
    const url = await cloudinary.api.resources({
      type: 'upload',
      prefix: 'prefix',
      max_results: 25,
      ...options
    });
    

   // 期望的响应对象
    /*
    RESPONSE object
 {
  "resources": [
    {
      "asset_id": "b1ce1d159bc3696e5a74d8b8aefbe707",
      "public_id": "face_center",
      "format": "jpg",
      "version": 1333013579,
      "resource_type": "image",
      "type": "upload",
      "created_at": "2012-03-29T09:32:59Z",
      "bytes": 128891,
      "width": 283,
      "height": 424,
      "backup": true,
      "access_mode": "public",
      "url": "http://res.cloudinary.com/demo/image/upload/v1333013579/face_center.jpg",
      "secure_url": "https://.../image/upload/v1333013579/face_center.jpg"
    },
    {
      "asset_id": "835d1cf89bd7c1b84dc4f53d35bc235f",
      "public_id": "12208495",
      "format": "jpg",
      "resource_type": "image",
      "type": "facebook",
      "created_at": "2012-10-06T17:18:52Z",
      "bytes": 0,
      "access_mode": "public",
      "url": "http://res.cloudinary.com/demo/image/facebook/12208495.jpg",
      "secure_url": "https://.../image/facebook/12208495.jpg"
    },
  ]
}
   */
    // ! 应该获取元数据
    const meta = await cloudinary.api.list_metadata_fields(options);

   // 期望的响应
  /*
{
  "metadata_fields": 
  [
    {
      "type": "date",
      "external_id": "available_date",
      "label": "Available date",
      "mandatory": false,
      "default_value": "2015-01-01",
      "validation": null,
      "default_disabled": false,
      "restrictions": {
        "readonly_ui": false
      }
    },
    {
      "type": "integer",
      "external_id": "in_stock",
      "label": "In stock",
      "mandatory": false,
      "default_value": 42,
      "validation": null,
      "default_disabled": false,
      "restrictions": {
        "readonly_ui": false
      }
    }
  ]
}
*/

      } catch (error) {
      console.error('error:', error);
  }
};
getGalleryFromCloudinary()

module.exports = getGalleryFromCloudinary;

我通过Cloudinary GUI为每个图像添加了元数据:

使用Node.js SDK从Cloudinary获取文件元数据。

我的目标是检索像我添加的那个“California Horses #1”一样的元数据字符串,它作为图像描述。

我有两个问题:

1)虽然 cloudinary.api.resources() 返回了带有相应的图像URL的正确响应对象,但 cloudinary.api.list_metadata_fields() 返回了一个空数组 []。是否有人熟悉Cloudinary SDK,并知道为什么会发生这种情况?

2)假设我成功返回了 cloudinary.api.list_metadata_fields() 预期的JSON对象...这并不意味着我将能够检索到我添加到图像中的“Californian Horses #1”标题。如果是这种情况...我如何将此字符串添加到任何响应对象中?

英文:

I'm building a website using React and storing my image assets on the cloudinary server. I want to create a scroll gallery with the image and a description.

Example:

// STATE
const [cloudImgData, fetchData] = useState([
{url: [&#39;url string&#39;, ..], meta: [&#39;metadata string&#39;]},
{url: [&#39;url string&#39;, ..], meta: [&#39;metadata string&#39;]},
...
])
const fetchIMGS = () =&gt; {
//...fetch images
} 
return (
&lt;div class=&quot;image_gallery&quot;&gt;
{cloudImgData.map((img) =&gt; {
return (
&lt;img src={img.url}&gt;
&lt;p&gt;{img.meta}&lt;/p&gt;
)
})}
&lt;/div&gt;
)

For the backend I've been using the Nodejs SDK and its methods, I'm using the Admin and Metadata APIs.

const cloudinary = require(&#39;cloudinary&#39;).v2;
require(&#39;dotenv&#39;).config();
const getGalleryFromCloudinary = async (exhibit) =&gt; {
try {
const options = { 
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API,
api_secret: process.env.CLOUD_SECRET_API,
secure: true
};
cloudinary.config(options);
// fetches URL
const url = await cloudinary.api.resources({
type: &#39;upload&#39;,
prefix: &#39;prefix&#39;,
max_results: 25,
...options
});
// EXPECTING
/*
RESPONSE object
{
&quot;resources&quot;: [
{
&quot;asset_id&quot;: &quot;b1ce1d159bc3696e5a74d8b8aefbe707&quot;,
&quot;public_id&quot;: &quot;face_center&quot;,
&quot;format&quot;: &quot;jpg&quot;,
&quot;version&quot;: 1333013579,
&quot;resource_type&quot;: &quot;image&quot;,
&quot;type&quot;: &quot;upload&quot;,
&quot;created_at&quot;: &quot;2012-03-29T09:32:59Z&quot;,
&quot;bytes&quot;: 128891,
&quot;width&quot;: 283,
&quot;height&quot;: 424,
&quot;backup&quot;: true,
&quot;access_mode&quot;: &quot;public&quot;,
&quot;url&quot;: &quot;http://res.cloudinary.com/demo/image/upload/v1333013579/face_center.jpg&quot;,
&quot;secure_url&quot;: &quot;https://.../image/upload/v1333013579/face_center.jpg&quot;
},
{
&quot;asset_id&quot;: &quot;835d1cf89bd7c1b84dc4f53d35bc235f&quot;,
&quot;public_id&quot;: &quot;12208495&quot;,
&quot;format&quot;: &quot;jpg&quot;,
&quot;resource_type&quot;: &quot;image&quot;,
&quot;type&quot;: &quot;facebook&quot;,
&quot;created_at&quot;: &quot;2012-10-06T17:18:52Z&quot;,
&quot;bytes&quot;: 0,
&quot;access_mode&quot;: &quot;public&quot;,
&quot;url&quot;: &quot;http://res.cloudinary.com/demo/image/facebook/12208495.jpg&quot;,
&quot;secure_url&quot;: &quot;https://.../image/facebook/12208495.jpg&quot;
},
]
}
*/
// ! SHOULD fetch metadata
const meta = await cloudinary.api.list_metadata_fields(options);
// EXPECTING 
/*
{
&quot;metadata_fields&quot;: 
[
{
&quot;type&quot;: &quot;date&quot;,
&quot;external_id&quot;: &quot;available_date&quot;,
&quot;label&quot;: &quot;Available date&quot;,
&quot;mandatory&quot;: false,
&quot;default_value&quot;: &quot;2015-01-01&quot;,
&quot;validation&quot;: null,
&quot;default_disabled&quot;: false,
&quot;restrictions&quot;: {
&quot;readonly_ui&quot;: false
}
},
{
&quot;type&quot;: &quot;integer&quot;,
&quot;external_id&quot;: &quot;in_stock&quot;,
&quot;label&quot;: &quot;In stock&quot;,
&quot;mandatory&quot;: false,
&quot;default_value&quot;: 42,
&quot;validation&quot;: null,
&quot;default_disabled&quot;: false,
&quot;restrictions&quot;: {
&quot;readonly_ui&quot;: false
}
}
]
}
*/
} catch (error) {
console.error(&#39;error:&#39;, error);
}
};
getGalleryFromCloudinary()
module.exports = getGalleryFromCloudinary;

I've added metadata to each image via the cloudinary gui:

使用Node.js SDK从Cloudinary获取文件元数据。

MY GOAL: is the retrieve a list of metadata strings like the one I added: "California Horses #1", which serve as the image description

I HAVE 2 ISSUES:

  1. While the cloudinary.api.resources() DOES return the correct response object with the accompanying image urls. The cloudinary.api.list_metadata_fields() returns an empty array []. Does anyone have any expertise with the cloudinary SDK and might know why this is happening?

  2. Let's say I do manage to return the expected JSON object with the cloudinary.api.list_metadata_fields()...this won't mean that I'll be able to retrieve the "Californian Horses #1" title that I added to the image. Should this be the case...how can I add this string to any of the response objects?

答案1

得分: 2

list_metadata_fields() 是与结构化元数据相关的方法,其目的是返回您在云中创建的任何结构化元数据字段定义。它不会返回云中资产的详细信息。
https://cloudinary.com/documentation/metadata_api#get_metadata_fields

在您的示例(屏幕截图)中,您正在填写资产的上下文元数据,并且 resources() 方法返回云中资产的详细信息。只有在您的 resources() 调用 options 中将 context 参数设置为 true 时,您才会在响应中收到上下文元数据。例如:

const url = await cloudinary.api.resources({
  type: 'upload',
  prefix: '...',
  max_results: 500,
  context: true
});

请参阅此方法的文档(https://cloudinary.com/documentation/admin_api#get_resources),其中详细介绍了可以传递的所有其他参数。

您还可以创建结构化元数据字段,并在 resources() 响应中默认返回它们,而不是上下文元数据。值得查看文档的以下部分,详细介绍了标签、上下文和结构化元数据之间的区别,以便根据您的需求选择存储此数据的最佳方法:
https://cloudinary.com/documentation/dam_manage_individual_assets#custom_metadata_comparison_table

resources() 方法是Admin API的一部分,应仅从服务器端调用,因为它依赖于应仅在后端公开的 API 密钥。获取资产详细信息(包括元数据)的另一种选择可能是从客户端使用资源列表 - 使用此功能,您可以发出包含 URL 的碎片标记作为 URL 的一部分的 GET 请求,并在响应中获得标记为指定标记的资产的详细信息,包括标签/上下文/结构化元数据。这样,您可以直接从客户端端获取数据,而无需服务器进行请求云中以获取数据。

英文:

list_metadata_fields() is a method relating to Structured metadata and its purpose is to return any Structured metadata field definitions you have created in your cloud. It will not return you details of assets from your cloud.
https://cloudinary.com/documentation/metadata_api#get_metadata_fields

In your example (screenshot), you are filling in the Contextual metadata of the asset and the resources() method returns details of assets from your cloud. You will get the Context metadata returned in the response only if you've passed the context parameter set to true in your resources() call options. E.g.

const url = await cloudinary.api.resources({
type: &#39;upload&#39;,
prefix: &#39;...&#39;,
max_results: 500,
context: true
});

Please see the Documentation for this method (https://cloudinary.com/documentation/admin_api#get_resources) which details all other parameters you can pass.

You can also create Structured metadata fields and use those instead of Contextual metadata. Those are returned by default in the resources() response. Worth checking out the following section of the Documentation that details the difference between tags, context and structured metadata so that you can choose the best method of storing this data based on your requirements:
https://cloudinary.com/documentation/dam_manage_individual_assets#custom_metadata_comparison_table

The resources() method is part of the Admin API which should only be called from the server side since it relies on the API Secret which should be exposed only on the backend. Another option for getting details of assets (including metadata) could be using Resource Lists from the client side - with this feature, you can make a GET request which includes a shard tag as part of the URL and in the response, you'll get the details of assets which are tagged with the specified tag, including tags/context/structured metadata. This way, you avoid needing your server to make the request to Cloudinary to get the data and you can grab it from the client side directly.

huangapple
  • 本文由 发表于 2023年6月9日 03:27:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定