Sitecore alternative to identify image from DAM or media library

·

2 min read

The Sitecore.Resources.Media.MediaManager.GetMediaUrl method is designed to access the friendly URL of a media item which is uploaded (created) in Sitecore CMS, because its Media field contains path to a blob that is stored in the database by default.

Sitecore Connect for Sitecore DAM is designed to insert a public link to Sitecore DAM media using Sitecore CMS “Image” field that contain the “Browse Sitecore DAM” command: https://docs.stylelabs.com/content/3.4.x/user-documentation/content-user-manual/integrate/sitecore-connect-for-sitecore-dam/overview.html

In this case, the Image field contains a public link with the host to the Sitecore DAM instance, so there is no need to generate a friendly URL of a media item.

URL to a media in this case is stored in the src attribute of the Image field in the following format:

https://SitecoreDAMinstance.com/api/public/content/123456789abcdefgh?v=63a4f0f0

We can use, for example, the following API to access such URLs:

Sitecore.Data.Items.Item itemWithImageField = master.GetItem("/sitecore/content/Home/ItemWithImageField");
Sitecore.Data.Fields.XmlField imageField = itemWithImageField.Fields["Image"];
string src = imageField.GetAttribute("src");

Then an image can be rendered as follows:

<img src="@src"/>

Solution

For most cases, we do have item extension to get MediaItem URL, it will be good to add condition to check the src attribute or use the MediaItem of the ImageField to identify image from Sitecore DAM or Sitecore media library. For example

public static string MediaUrl(this Item item, ID fieldId, MediaUrlBuilderOptions options = null)
        {
            ImageField imageField = item?.Fields[fieldId];
            if (imageField.MediaItem == null)
            {
                // Sitecore DAM: Get src attribute
                XmlField imageDAMField = item?.Fields[fieldId];
                string src = imageDAMField.GetAttribute("src");
                return src;
            }
            else
            {
                // Sitecore Media Library: Perform the GetMediaUrl method
                if (imageField == null || imageField.MediaItem == null)
                {
                    return string.Empty;
                }

                return imageField.MediaItem.MediaUrl(options);
            }
        }

Hope the above help someone who is new to Sitecore Content Hub