Tuesday 9 February 2021

Sitecore - Check Media Item size on Upload

Hello Sitecore Developers,

We had a unique requirement from client where they want to limit the Upload size for Images and PDFs to 600 KB and 10 MB respectively.

This can be handled through a small setting in the sitecore.config where we can adjust the default value of the media items to be uploaded. If we change the value from 500MB to any other size (i.e. 1 MB, 2MB etc.) it won’t allow to upload the items more than the specified size limit.



<!-- MEDIA - MAX SIZE IN DATABASE

The maximum allowed size of media intended to be stored in a database (binary blob).

This value must be less than the ASP.NET httpRuntime.maxRequestLength setting.

Default value: 500MB

-->

<setting name="Media.MaxSizeInDatabase" value="500MB" />


Since we only want to make this change for the Images and PDFs this solution wouldn’t be feasible for us. Instead we need to build something custom.

We started looking into the Sitecore Kernel through reflector to find out the Pipeline/Processor responsible to check the size of media items.

The Pipeline which handles the Upload request for Media Items is Upload and the processor is Check Size. We decided to replace the processor with our custom processor.

As a best practice, created custom patch file.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">

<sitecore>

<processors>

<uiUpload>

<processor mode="on" type="[YOUR_PROJECT_NAME].Pipelines.Upload.CheckImageandPdfSize, [YOUR_PROJECT_NAME]" patch:instead="processor[@type='Sitecore.Pipelines.Upload.CheckSize, Sitecore.Kernel']"></processor>

</uiUpload>

</processors>

</sitecore>

</configuration>

 

Custom Processor

public class CheckImageandPdfSize : UploadProcessor
    {
        public List<string> ValidExtensions { get; set; }
 
        public CheckImageandPdfSize()
        {
            ValidExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".tiff", ".tif", ".gif" };
        }
 
        public void Process(UploadArgs args)
        {
            Assert.ArgumentNotNull((object)args, nameof(args));
 
            if (args.Destination == UploadDestination.File)
                return;
 
            foreach (string index in args.Files)
            {
                HttpPostedFile file = args.Files[index];
                if (!string.IsNullOrEmpty(file.FileName))
                {
                    bool isPDF = Path.GetExtension(file.FileName).Equals(".pdf", StringComparison.OrdinalIgnoreCase);
 
                    if (isPDF && (long)file.ContentLength > AllowedPDFSize)
                    {
                        string text = StringUtil.EscapeJavascriptString(file.FileName);
                        args.UiResponseHandlerEx.FileCannotBeUploaded(text, StringUtil.EscapeJavascriptString($"You must select a PDF file smaller than {(object)MainUtil.FormatSize(AllowedPDFSize)} in size."));
                        args.ErrorText = $"The file {(object)text} is too big to be uploaded. You must upload PDF file smaller than {(object)MainUtil.FormatSize(AllowedPDFSize)} in size.";
                        args.AbortPipeline();
                        break;
                    }
                    else if ((long)file.ContentLength > AllowedImageSize && ValidExtensions.Any(ext => ext.Equals(Path.GetExtension(file.FileName))))
                    {
                        string text = StringUtil.EscapeJavascriptString(file.FileName);
                        args.UiResponseHandlerEx.FileCannotBeUploaded(text, StringUtil.EscapeJavascriptString($"You must select an image smaller than {(object)MainUtil.FormatSize(AllowedImageSize)} in size with one of the following file extensions : .jpg, .png, .gif, .jpeg, .tif, .tiff "));
                        args.ErrorText = $"The file {(object)text} is too big to be uploaded. You must select an image smaller than {(object)MainUtil.FormatSize(AllowedImageSize)} in size with one of the following file extensions : .jpg, .png, .gif, .jpeg, .tif, .tiff.";
                        args.AbortPipeline();
                        break;
                    }
                }
            }
        }
 
        public static long AllowedImageSize
        {
            get
            {
                return Settings.GetLongSetting("Media.AllowedImageSize", 614400); //600 KB = 614400
            }
        }
        public static long AllowedPDFSize
        {
            get
            {
                return Settings.GetLongSetting("Media.AllowedPDFSize", 10485760); //10 MB = 10485760
            }
        }
    }

  

Now, when you try to upload a file using Media Library upload and if the size is more

than the specified limit it won’t allow to upload the file (i.e. image/PDF)

For Image,

 

 

 

 

 

 

For PDF,

 

 

 

 

 

 

This would also work when you try to upload the image or PDF using Upload Files(Advanced) and through sitecore field.