Skip to content

Instantly share code, notes, and snippets.

@sitereactor
Last active July 12, 2023 02:33
Show Gist options
  • Save sitereactor/04ffad4d173f2aac7667 to your computer and use it in GitHub Desktop.
Save sitereactor/04ffad4d173f2aac7667 to your computer and use it in GitHub Desktop.
Renaming an image when its uploaded to a property with Alias "umbracoFile", but before its saved. The name of the image will be changed to the name of the folder it resides in. This is using the Saving event in the MediaService in Umbraco.
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.IO;
using Umbraco.Core.Services;
namespace Startup
{
public class MediaEventHandler : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
MediaService.Saving += MediaService_Saving;
}
void MediaService_Saving(IMediaService sender, SaveEventArgs<Umbraco.Core.Models.IMedia> e)
{
var fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
foreach (var media in e.SavedEntities)
{
//Assuming Media item only has one umbracoFile property to handle
var umbracoFileProperty = media.Properties["umbracoFile"];
//Path will have this format /media/1234/koala.jpg
var imagePath = umbracoFileProperty.Value.ToString();
var fullPath = fs.GetFullPath(imagePath);
var relativePath = fs.GetRelativePath(fullPath);
//Update the path for each thumbnail
var thumbnails = fs.GetThumbnails(relativePath);
thumbnails.ForEach(thumbnail => SetNewImagePath(thumbnail, true, fs));
//Update the path for the 'main' image
var newImagePath = SetNewImagePath(relativePath, false, fs);
//Update property with new image path
umbracoFileProperty.Value = newImagePath;
//Remove old image and thumbnails
fs.DeleteFile(relativePath, true);
}
}
private string SetNewImagePath(string imagePath, bool isThumbnail, MediaFileSystem fs)
{
var file = fs.GetFileName(imagePath);
//Extract name of file
var fileNameNoExt = file.Substring(0, file.LastIndexOf('.'));
if (isThumbnail)
fileNameNoExt = fileNameNoExt.Replace("_thumb", "").Replace("_big-thumb", "");
//Extract name of directory
var folderName = imagePath.Substring(0, imagePath.IndexOf('\\'));
//Assemble new path
var newImagePath = imagePath.Replace(fileNameNoExt, folderName);
//Move file to new path, and override any existing image
using (var fileStream = fs.OpenFile(imagePath))
{
fs.AddFile(newImagePath, fileStream, true);
}
//Return the full path as that is what we want to store
return fs.GetFullPath(newImagePath);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment