Valid for Sitecore
5.3.1
How can a user acquire a media item from the file field? The file field points to a valid media item.
Q:
How can a user acquire a media item from the file field? The file field points to a valid media item.
A:
Sitecore version: tested with Sitecore CMS V5.3.1 rev.070727.
There is a number of ways to get the image referenced by the file field.
- Getting the SRC attribute:
First we need to get the instance of the XML field by its name:
Sitecore.Data.Fields.XmlField fileField = item.Fields["File"];
Then we need to get the attribute of the field value using the GetAttribute method:
imageControl.ImageUrl = Sitecore.StringUtil.EnsurePrefix('/', fileField.GetAttribute("src"));
After that we can assign the URL to an ASP.NET image control.
- Getting the media item:
First we need to get the instance of the XML field by its name:
Sitecore.Data.Fields.XmlField fileField = item.Fields["File"];
Now we can read the media ID using the same approach.
Sitecore.Data.ID mediaID = Sitecore.Data.ID.Parse(fileField.GetAttribute("mediaid"));
After that we can search for the media item in the context database:
Sitecore.Data.Items.MediaItem mediaItem = Sitecore.Context.Database.Items[mediaID];
If the item is found, we can read any property of the MediaItem object:
if (mediaItem != null)
{
imageControl.ImageUrl = Sitecore.StringUtil.EnsurePrefix('/', mediaItem.InnerItem["Path"]);
}