Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Sebastian Dammark 583 posts 1407 karma points
    May 18, 2021 @ 09:12
    Sebastian Dammark
    0

    Configuration for renaming media upload ?

    When uploading files to Media, the created media gets the name from the uploaded file.

    Is there a configuration for how these naming conventions ?

    Now it's like this

    • Filename: this-is-a-pdf-file.jpg
    • Medianame: This Is A Pdf File

    Would it be possible to configure it to do like this:

    • Medianame: This is a pdf file
  • Vlael Layug 13 posts 115 karma points c-trib
    May 28, 2021 @ 15:34
    Vlael Layug
    0

    Hello Sebastian,

    I've look inside the MediaController where the media uploader is using the PostAddFile() method and it's using the ToFriendlyName() to format the media name.

    You can hook into the Media Service Events. https://our.umbraco.com/documentation/Reference/Events/MediaService-Events

    Here's a sample proof of concept that I've played around using the MediaService.Saving event.

    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class MediaComposer : ComponentComposer<SubscribeToMediaSavingEventComponent>
    {
    }
    
    public class SubscribeToMediaSavingEventComponent : IComponent
    {
        public void Initialize()
        {
            MediaService.Saving += MediaService_Saving;
        }
    
        private void MediaService_Saving(Umbraco.Core.Services.IMediaService sender, Umbraco.Core.Events.SaveEventArgs<Umbraco.Core.Models.IMedia> e)
        {
            foreach (var mediaItem in e.SavedEntities)
            {
                if (mediaItem.ContentType.Alias == "Image")
                {
                    //overwrites the media name
                    mediaItem.Name = ToSentenceCase(mediaItem.Name);
                }
            }
        }
    
        /// <summary>
        /// Converts a string to sentence case.
        /// </summary>
        /// <param name="input">The string to convert.</param>
        /// <returns>A string</returns>
        private static string ToSentenceCase(string input)
        {
            if (input.Length < 1)
                return input;
    
            string sentence = input.ToLower();
            return sentence[0].ToString().ToUpper() +
               sentence.Substring(1);
        }
    
        public void Terminate()
        {
            //unsubscribe during shutdown
            MediaService.Saving -= MediaService_Saving;
        }
    }
    

    I got the "ToSentenceCase()" method here.

    Regards,
    Vlael

Please Sign in or register to post replies

Write your reply to:

Draft