Skip to content

Instantly share code, notes, and snippets.

@tcmorris
Last active June 15, 2017 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcmorris/800c9ace2bb083052b44bbbb72be6e29 to your computer and use it in GitHub Desktop.
Save tcmorris/800c9ace2bb083052b44bbbb72be6e29 to your computer and use it in GitHub Desktop.
Event Handler for checking media uploads in Umbraco
/// <summary>
/// MediaEventHandler
/// Will hook into the MediaService saving event and apply some custom logic to ensure we have a valid media file.
/// </summary>
public class MediaEventHandler : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
MediaService.Saving += MediaService_Saving;
}
private static void MediaService_Saving(IMediaService sender, SaveEventArgs<IMedia> e)
{
foreach (var mediaItem in e.SavedEntities)
{
// validate
if (IsValidMedia(mediaItem) == false)
{
// report issue to user
e.CancelOperation(new EventMessage(
"Media not saved",
"Sorry, but the provided file is invalid for this type of media. Please upload a new file.",
EventMessageType.Error)
);
}
}
}
/// <summary>
/// Ensures the uploaded file is valid for the provided media type
/// </summary>
/// <param name="mediaItem">The media item</param>
/// <returns>True if valid</returns>
private static bool IsValidMedia(IMedia mediaItem)
{
// if standard file or folder, assume valid
var alias = mediaItem.ContentType.Alias;
if (alias == "File" || alias == "Folder")
{
return true;
}
// have we got a file?
var umbracoFile = mediaItem?.GetValue<string>("umbracoFile");
if (string.IsNullOrEmpty(umbracoFile))
{
return false;
}
var validFile = false;
var extension = Path.GetExtension(umbracoFile).ToLower();
// get the posted file and check the file extension
var postedFile = HttpContext.Current.Request.Files.Get(0);
if (alias == "Image")
{
switch (extension)
{
case ".jpg":
case ".jpeg":
validFile = IsValidImage(ImageFormat.Jpeg, postedFile.InputStream);
break;
case ".png":
validFile = IsValidImage(ImageFormat.Png, postedFile.InputStream);
break;
case ".gif":
validFile = IsValidImage(ImageFormat.Gif, postedFile.InputStream);
break;
}
}
else if (alias == "Video" && extension == ".mp4")
{
validFile = postedFile.ContentType == "video/mp4";
}
else if (alias == "Svg" && extension == ".svg")
{
validFile = postedFile.ContentType == "image/svg+xml";
}
return validFile;
}
/// <summary>
/// Validates posted image file is of a correct format by loading to an object and checking format/catching exception
/// </summary>
/// <param name="expectedFormat">Image format to compare to</param>
/// <param name="postedFile">Posted file</param>
/// <param name="filePath">Path to file on disk</param>
/// <returns>True if matches image format</returns>
private static bool IsValidImage(ImageFormat expectedFormat, Stream postedFile, string filePath = "")
{
try
{
// Create image object from posted file stream or path
var img = postedFile != null ? Image.FromStream(postedFile) : Image.FromFile(filePath);
// Two image formats can be compared using the Equals method
// See http://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat.aspx
return img.RawFormat.Equals(expectedFormat);
}
catch (Exception ex)
{
// catch exception and return false
LogHelper.Error<MediaEventHandler>("Error saving media item.", ex);
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment