How to retrieve Sitecore media items from media url?
Asked Answered
T

2

5

How to retrieve Sitecore media item from the URL we have?

The URL is dynamic URL e.g. /~/media/14BDED00E4D64DFD8F74019AED4D74EB.ashx.

This is generated when you add item in rich text field.

Theca answered 26/6, 2013 at 7:58 Comment(0)
E
10

You can use the code below:

DynamicLink dynamicLink;
if (!DynamicLink.TryParse("/~/media/14BDED00E4D64DFD8F74019AED4D74EB.ashx", out dynamicLink))
    return;
MediaItem mediaItem = Sitecore.Context.Database.GetItem(dynamicLink.ItemId, dynamicLink.Language ?? Sitecore.Context.Language);
Eubanks answered 26/6, 2013 at 8:9 Comment(0)
H
3

When adding an item in the Rich Text field, you can use the FieldRenderer to render out the output - Sitecore will then create the correct URL automatically. That way you won't even have to worry about the URL.

The FieldRenderer control can be used like so:

<sc:FieldRenderer ID="renderer" runat="server" FieldName="fieldname" />

Or if you're using XSLT:

<sc:text field="fieldname" />

In codebehind you could do something like

FieldRenderer.Render(Sitecore.Context.Item, fieldname);
Haden answered 26/6, 2013 at 8:12 Comment(2)
While this is true, there still is value in being able to get the media item directly. Parsing a rich text field in a pipeline component could be used to ensure all linked media items are also published.Kythera
That's a fair point, although I think I'd use the link database for functionality such as that - but there can definitely be value in having the actual media item.Haden

© 2022 - 2024 — McMap. All rights reserved.