如何在 sitecore 中获取媒体项目详细信息?

How to get media item details in sitecore?

我目前正在 sitecore.So 中生成图像站点地图,我需要网站特定 url 中使用的所有图像。

在这里我需要获取使用媒体项目的所有项目的详细信息..否则我需要找到项目(url)中使用的所有媒体项目(图像)是什么站点核心。

我试图从一个项目中获取图像字段并且它工作正常但我需要的是获取项目中使用的所有图像,这些图像是通过演示详细信息添加的。

 Item currentitem = master.GetItem("/sitecore/content/International/Cars/New models/All new XC90");
 public static string GetImageURL(Item currentItem)
        {
            string imageURL = string.Empty;
            Sitecore.Data.Fields.ImageField imageField = currentItem.Fields["Image"];
            if (imageField != null && imageField.MediaItem != null)
            {
                Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);
                imageURL = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));
            }
            return imageURL;
        }

由于页面由多个组件组成,您需要遍历这些组件、检索所有数据源项目并检查字段值。不要忘记图像也可以放在富文本字段中。

为了确保您捕捉到所有这些,您最好制作一个WebClient call back to the site, essentially scraping the rendered HTML and then using HTMLAgilityPack/FizzlerEx/CsQuery到return所有图像。如果需要,您可以过滤到仅来自媒体库或特定位置的内容。

using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;

//get the page
HtmlWeb web = new HtmlWeb();
HtmlDocument document = web.Load("http://example.com/requested-page");
HtmlNode page = document.DocumentNode;

//loop through all images on the page
foreach(HtmlNode item in page.QuerySelectorAll("img"))
{
    var src = item.Attributes["src"].Value;
    // do some stuff
}

如果您只想获取媒体库中引用的图像,那么您可以限制查询:

foreach(HtmlNode item in page.QuerySelectorAll("img[src^='/-/media/']"))
{
    //do stuff
    ...
}

正如 jammykam 所指出的,一个页面可能由多个组件组成。但是,发出 html 的实时请求可能并不总是最佳的。

另一种解决方案是使用 Sitecore ContentSearch。您可以创建一个存储的计算字段,其中包含页面项目上所有图像的列表。在 运行 时间内提取会快得多,您可以花费更多 CPU 周期在索引时间内获得准确的图像列表。

计算索引字段可以是 guid(媒体 itme id)列表或图像 url 或适合您需要的任何自定义格式。

在索引期间,您可以使用LinkDatabase 查找引用的项目并筛选出您需要的媒体项目。因此,您将获得从任何字段引用的图像,包括富文本字段中的嵌入图像。

如前所述,您可以对项目本身和页面布局使用的引用项目执行这些操作。您可以遍历从 item.Visualization.GetRenderings

获得的项目参考列表

遍历 sitecore 中的所有页面是一项非常繁重的任务,它还会导致获得不需要的图像,例如徽标和其他 header 图像。您应该考虑在页面模板上添加 'Sitemap Images' 树列表字段以包含页面的所有相关图像。