Sitecore media upload with specific file extensions

 We had a requirement to upload files in the media library but certain file extensions like .exe, and .ps1 are to be blocked, giving the customer flexibility in the future they can have the flexibility to enter the extension in the config file that is to be blocked or allowed.

So we have an uploadProcessor that we created as follows:

using Sitecore.Diagnostics;
using Sitecore.Pipelines;
using Sitecore.Pipelines.Upload;
using Sitecore.Zip;
using System.Collections.Generic;
using System.IO;
using System.Web;

namespace MyProject.Feature.Media
{
  public class MediaFilter : UploadProcessor
  {
    private bool _isAllowed;

    private string _extensions;

    public MediaFilter(string allowed, string blocked)
    {
      if (!string.IsNullOrEmpty(allowed))
      {
        _isAllowed = true;
        _extensions = allowed.Replace(" ", "").ToLower();
      }
      else if (!string.IsNullOrEmpty(blocked))
      {
        _isAllowed = false;
        _extensions = blocked.Replace(" ", "").ToLower();
      }
    }

    public void Process(UploadArgs args)
    {
      Assert.ArgumentNotNull((object)args, "args");
      if (string.IsNullOrEmpty(_extensions))
      {
        return;
      }
      List<string> list = PrepareExtensions(_extensions);
      foreach (string file in args.Files)
      {
        HttpPostedFile httpPostedFile = args.Files[file];
        if (string.IsNullOrEmpty(httpPostedFile.FileName))
        {
          continue;
        }
        if (UploadProcessor.IsUnpack(args, httpPostedFile))
        {
          ZipReader val = new ZipReader(httpPostedFile.InputStream);
          try
          {
            foreach (ZipEntry entry in val.Entries)
            {
              string text = Path.GetExtension(entry.Name.ToLower()).TrimStart('.');
              bool flag = list.Contains(text);
              if ((!_isAllowed || !flag) && ((!_isAllowed && flag) || (_isAllowed && !flag)))
              {
                HttpContext.Current.Response.Write("<script type=\"text/JavaScript\">alert(\"Uploading files with ." + text + " extension is restricted\");</script>");
                Log.Audit($"Upload restricted: {entry.Name}", (object)this);
                new Done().Process(args);
                ((PipelineArgs)args).AbortPipeline();
                return;
              }
            }
          }
          finally
          {
            httpPostedFile.InputStream.Position = 0L;
          }
        }
        string text2 = Path.GetExtension(httpPostedFile.FileName.ToLower()).TrimStart('.');
        bool flag2 = list.Contains(text2);
        if ((!_isAllowed || !flag2) && ((!_isAllowed && flag2) || (_isAllowed && !flag2)))
        {
          HttpContext.Current.Response.Write("<script type=\"text/JavaScript\">alert(\"Uploading files with ." + text2 + " extension is restricted\");</script>");
          Log.Audit($"Upload restricted: {httpPostedFile.FileName}", (object)this);
          new Done().Process(args);
          ((PipelineArgs)args).AbortPipeline();
          break;
        }
      }
    }

    private List<string> PrepareExtensions(string csvExtensions)
    {
      string[] array = csvExtensions.Split(',');
      List<string> list = new List<string>();
      string[] array2 = array;
      foreach (string item in array2)
      {
        list.Add(item);
      }
      return list;
    }
  }
}

Then we have the respective config file as 

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <processors>
            <uiUpload>
                <processor mode="on" type="MyProject.Feature.Media.MediaFilter, MyProject.Feature.Media" patch:before="*[1]">
                    <param name="allowed" desc="Allowed extensions (comma separated)"></param>
                    <param name="blocked" desc="Blocked extensions (comma separated)">exe,dll,bat</param>
                </processor>                
            </uiUpload>
        </processors>       
    </sitecore>    
</configuration>

So after this, we had one more requirement to edit the error message at the time of uploading the media so that a user-friendly message can be generated if while uploading we get any error. This is covered on the link https://sitecorepeanuts.blogspot.com/2024/06/sitecore-media-upload-with-user.html to avoid the lengthy article and keep the context separate.

1 comment:

  1. https://sitecorepeanuts.blogspot.com/2024/06/sitecore-media-upload-with-specific.html

    ReplyDelete

Creating Solr core for sitecore using command prompt

We setup the solr cores using command “C:\solr8985\sc103solr-8.11.2\bin>solr.cmd create -c sitecore_sxa_web_index -d sitecore_configset” ...