Ben Nitti
Apr 22, 2021
  1753
(3 votes)

Retrieving, storing file size information during upload

While presenting media content available for public download, it might be helpful to provide the file size, particularly for mobile users who may not want to save large files to their phone. 

This can be performed on any IContentMedia type by extending the content model and using an initialization module to retrieve and save the file size information. 

For this example, I'll create a custom media type for storing PDF, Word and Excel documents with a read only property to store the file size:

    [MediaDescriptor(ExtensionString = "pdf,docx,xlsx")]
    public class DocumentMediaType : MediaData, IHasFileSize
    {
        [Editable(false)]
        [Display(Order = 10, GroupName = SystemTabNames.Settings, Name = "File Size")]
        public virtual string FileSize { get; set; }
    }

I'm implementing an interface I called IHasFileSize:

    public interface IHasFileSize
    {
        string FileSize { get; set; }
    }

After that I can create the initialization module and attach to the save and create events to store the file size data:

    [InitializableModule]
    [ModuleDependency(typeof(ServiceContainerInitialization))]
    public class FileBasedEventsInitialization : IInitializableModule
    {
        // attach to both the CreatingContent and SavingContent events
        public void Initialize(InitializationEngine context)
        {
            IContentEvents eventRegistry = ServiceLocator.Current.GetInstance<IContentEvents>();

            eventRegistry.CreatingContent += SavingMedia;
            eventRegistry.SavingContent += SavingMedia;
        }

        private void SavingMedia(object sender, EPiServer.ContentEventArgs e)
        {

            if (!(e.Content is IContentMedia))
                return;

            IContentMedia media = e.Content as IContentMedia;

            string fileSize = GetFileSizeDisplay(media);

            if (media is IHasFileSize file)
            {
                file.FileSize = fileSize;
            }
        }

        private string GetFileSizeDisplay(IContentMedia media)
        {
            if (media?.BinaryData != null)
            {
                using (var stream = media.BinaryData.OpenRead())
                {
                    return FormatBytes(stream.Length);
                }
            }

            return string.Empty;
        }

        public void Uninitialize(InitializationEngine context)
        {
            IContentEvents eventRegistry = ServiceLocator.Current.GetInstance<IContentEvents>();

            eventRegistry.CreatingContent -= SavingMedia;
            eventRegistry.SavingContent -= SavingMedia;
        }

    }

This method is used for formatting the file size with the correct unit of measurement:

        private static string FormatBytes(long bytes)
        {
            string[] uom = { "B", "KB", "MB", "GB" };

            int i;

            double size = bytes;

            for (i = 0; i < uom.Length && bytes >= 1024; i++, bytes /= 1024)
            {
                size = bytes / 1024.0;
            }

            return $"{size:0.##} {uom[i]}";
        }

Thanks for reading, and enjoy displaying your new custom FileSize property!



Apr 22, 2021

Comments

Please login to comment.
Latest blogs
Opti ID overview

Opti ID allows you to log in once and switch between Optimizely products using Okta, Entra ID, or a local account. You can also manage all your use...

K Khan | Jul 26, 2024

Getting Started with Optimizely SaaS using Next.js Starter App - Extend a component - Part 3

This is the final part of our Optimizely SaaS CMS proof-of-concept (POC) blog series. In this post, we'll dive into extending a component within th...

Raghavendra Murthy | Jul 23, 2024 | Syndicated blog

Optimizely Graph – Faceting with Geta Categories

Overview As Optimizely Graph (and Content Cloud SaaS) makes its global debut, it is known that there are going to be some bugs and quirks. One of t...

Eric Markson | Jul 22, 2024 | Syndicated blog

Integration Bynder (DAM) with Optimizely

Bynder is a comprehensive digital asset management (DAM) platform that enables businesses to efficiently manage, store, organize, and share their...

Sanjay Kumar | Jul 22, 2024

Frontend Hosting for SaaS CMS Solutions

Introduction Now that CMS SaaS Core has gone into general availability, it is a good time to start discussing where to host the head. SaaS Core is...

Minesh Shah (Netcel) | Jul 20, 2024

Optimizely London Dev Meetup 11th July 2024

On 11th July 2024 in London Niteco and Netcel along with Optimizely ran the London Developer meetup. There was an great agenda of talks that we put...

Scott Reed | Jul 19, 2024