Try our conversational search powered by Generative AI!

Ben Nitti
Apr 22, 2021
  1722
(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
Product Listing Page - using Graph

Optimizely Graph makes it possible to query your data in an advanced way, by using GraphQL. Querying data, using facets and search phrases, is very...

Jonas Bergqvist | Jul 5, 2024

Optimizely Search and Navigation - Part 2 - Filter Tips

Introduction Continuing from Part 1 – Search Tips , today I will share the next part – filter tips. The platform versions used for this article are...

Binh Nguyen Thi | Jul 1, 2024

Integrating HubSpot CRM without the MA Connector

Have HubSpot CRM? Want to push user data into it from Optimizely? Don’t have any personalisation requirements with that data? Don’t want to pay $80...

Matt Pallatt | Jun 27, 2024

Keeping the website secure by updating external packages

Did you see the latest warning from Optimizely to update this package with a critical security warning? https://world.optimizely.com/documentation/...

Daniel Ovaska | Jun 27, 2024

Optimizely CMS image anonymization now available for Linux!

The famous image anonymization add-on for Optimizely CMS, with at least 5 downloads, is now finally available for use on Linux. Supports simultaneo...

Tomas Hensrud Gulla | Jun 25, 2024 | Syndicated blog

Remove a segment from the URL in CMS 12

Problem : I have created thousands of pages dynamically using schedule jobs with different templates (e.g. one column, two columns, etc..) and stor...

Sanjay Kumar | Jun 21, 2024