Created
March 21, 2012 18:10
-
-
Save tomfulton/2150553 to your computer and use it in GitHub Desktop.
Umbraco - GetMediaByPath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Gets the media item by it's file path | |
/// </summary> | |
/// <remarks> | |
/// Example usage: Use in conjunction with HtmlAgilityPack or WYSIWYG.xslt to parse your RTE for Media Images, grab associated | |
/// properties from the Media node, and render them in your output (think alt tags, captions, etc). | |
/// TODO: support non "/media" directory, cleanup & further testing | |
/// </remarks> | |
/// <param name="mediaPath">Path to the uploaded file in the media directory</param> | |
/// <returns>Media node which contains the specified file</returns> | |
public static Media GetMediaByPath(string mediaPath) | |
{ | |
// First, try simply searching the XML for this file (quick way) | |
// The only case this wouldn't hit is an image inserted in the RTE and resized (renamed to /media/xxxx/filename_YYYxZZZ.jpg - not stored in XML) | |
var media = uComponents.Core.uQuery.GetMediaByXPath("//Image [umbracoFile = '" + mediaPath + "']").FirstOrDefault(); | |
if (media != null) | |
return media; | |
// If we didn't find it in the XML, let's check by the PropertyID in the path | |
int propertyId = GetMediaPropertyId(mediaPath); | |
if (propertyId == 0) | |
return null; | |
var property = new Property(propertyId); | |
var content = Media.GetContentFromVersion(property.VersionId); | |
media = new Media(content.Id); | |
if (media.Id > 0) | |
return media; | |
return null; | |
} | |
private static int GetMediaPropertyId(string mediaPath) | |
{ | |
string[] pathParts = mediaPath.Split('/'); | |
int retVal = 0; | |
// note empty [0] so add +1 to count | |
if (pathParts.Count() == 3) | |
{ | |
// Media path is in UploadAllowDirectories format (/media/xxxx-file.ext) | |
// ... not using UmbracoSettings.UploadAllowDirectories so we can handle situation where setting may have been changed mid-install | |
var fileParts = pathParts[2].Split('-'); | |
int.TryParse(fileParts[0], out retVal); | |
} | |
else if (pathParts.Count() == 4) | |
{ | |
// Standard media path format /media/xxxx/file.ext | |
int.TryParse(pathParts[2], out retVal); | |
} | |
return retVal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment