Search code examples
umbracoumbraco7

Limiting the size of upload and the file type for umbraco media picket


Trying to select media via dialogService like this

  dialogService.mediaPicker({
            startNodeId: undefined,
            multiPicker: false,
            cropSize: undefined,
            showDetails: true,
            callback: function (data) {

             }

Is there some way to customise this media picker config and only allow certain media types and specify size as well


Solution

  • I think your best option would be to create an event handler for the Saving event of the MediaService and check for your conditions before the file is saved.

    More info here: https://our.umbraco.com/Documentation/Getting-Started/Code/Subscribing-To-Events/

    public class RestrictMediaTypeAndSize : ApplicationEventHandler
        {
    
            protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
            {
                MediaService.Saving += MediaService_Saving;
            }
    
            private void MediaService_Saving(IMediaService sender, Umbraco.Core.Events.SaveEventArgs<Umbraco.Core.Models.IMedia> e)
            {
                foreach (var media in e.SavedEntities)
                {
                    //you can check for other types of content
                    if (media.ContentType.Alias == Image.ModelTypeAlias)
                    {
                        var fileExtension = GetFileExtension(media);
                        if (!HasAllowedExtension(fileExtension))
                        {
                            //we cancel the saving process
                            e.Cancel = true;
    
                            //we send a message to the user.
                            var errorMessage = new EventMessage("Error", $"Files of type {fileExtension} are not allowed.");
                            e.Messages.Add(errorMessage);
    
                            //we found an error so we exit the foreach loop to finish the execution.
                            break;
                        }
    
                        if (!HasValidDimensions(media))
                        {
                            //we cancel the saving process
                            e.Cancel = true;
    
                            //we send a message to the user.
                            var errorMessage = new EventMessage("Error", "Files with a size of (whatever your restrictions) are not allowed.");
                            e.Messages.Add(errorMessage);
    
                            //we found an error so we exit the foreach loop to finish the execution.
                            break;
                        }
                    }
                }
            }
    
            private bool HasAllowedExtension(string fileExtension)
            {
                string[] allowedExtensions = new string[] { ".jpg", ".png" };
                return allowedExtensions.Contains(fileExtension);
            }
    
            private bool HasValidDimensions(IMedia media)
            {
                //take the image dimensions for the properties populated when you upload the file.
                var height = (int)media.Properties["umbracoHeight"].Value;
                var width = (int)media.Properties["umbracoWidth"].Value;
    
                //check for whatever conditions you want.
                return height < 1000 && width < 2000;
            }
    
            private string GetFileExtension(IMedia media)
            {
                //The umbracoFile Propery is a Json object and we need the src property from it which is the file path.
                var filePath = JObject.Parse(media.Properties["umbracoFile"].Value.ToString()).SelectToken("$.src").Value<string>();
                return System.IO.Path.GetExtension(filePath);
            }
        }