You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Umbraco技术咨询:如何遍历内容保存事件及页面内容并检查图片宽度

Great question! Let's break down how to achieve this step by step, assuming you're working with Umbraco (since Document Type and Image Picker are core Umbraco concepts):

Validate Image Width on Save/Publish

Step 1: Hook into Content Events

First, you need to register an event handler to intercept the save/publish action. For modern Umbraco (v9+), using notification handlers is the recommended approach. This lets you run your validation logic before the content is saved or published.

using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;

// Composer to register our handler
public class ImageValidationComposer : IComposer
{
    public void Compose(IUmbracoBuilder builder)
    {
        // Hook into the "before save" event (use ContentPublishedNotification for post-publish)
        builder.AddNotificationHandler<ContentSavingNotification, ImageValidationHandler>();
    }
}

// The actual handler that does the validation
public class ImageValidationHandler : INotificationHandler<ContentSavingNotification>
{
    private readonly IMediaService _mediaService;

    // Inject the Media Service to fetch image details
    public ImageValidationHandler(IMediaService mediaService)
    {
        _mediaService = mediaService;
    }

    public void Handle(ContentSavingNotification notification)
    {
        // Traverse all content items being saved
        foreach (var content in notification.SavedEntities)
        {
            // Target only your specific document type
            if (!content.ContentType.Alias.Equals("yourDocumentTypeAlias", StringComparison.OrdinalIgnoreCase))
                continue;

            // Get the Image Picker property value
            ValidateImagePickerContent(content, notification);
        }
    }
}

Step 2: Traverse Image Picker Items & Check Width

Add this method inside the ImageValidationHandler class to iterate over the Image Picker content and validate each image's width:

private void ValidateImagePickerContent(IContent content, ContentSavingNotification notification)
{
    // Get the Image Picker property (adjust alias to match your property)
    var mediaPickerValue = content.GetValue<MediaPickerValue>("yourImagePickerAlias");
    
    // Skip if no images are selected
    if (mediaPickerValue == null || !mediaPickerValue.Ids.Any())
        return;

    // Iterate over each selected image
    foreach (var mediaId in mediaPickerValue.Ids)
    {
        // Fetch the media item from Umbraco's media library
        var imageMedia = _mediaService.GetById(mediaId);
        if (imageMedia == null)
            continue;

        // Get the image's width (Umbraco stores this in "umbracoWidth" by default)
        var imageWidth = imageMedia.GetValue<int?>("umbracoWidth");
        
        // Apply your width validation rule
        if (imageWidth == null || imageWidth < 1200) // Example: minimum 1200px width
        {
            // Cancel the save operation and show an error message
            notification.CancelOperation(new EventMessage(
                "Validation Failed",
                $"Image '{imageMedia.Name}' is too small! Minimum required width is 1200px (current: {imageWidth ?? 0}px).",
                EventMessageType.Error));
            return; // Stop processing once an invalid image is found
        }
    }
}

Key Notes:

  • Replace yourDocumentTypeAlias with the alias of your target document type.
  • Replace yourImagePickerAlias with the alias of your Image Picker property.
  • Use ContentPublishedNotification instead of ContentSavingNotification if you want to validate after publish (though canceling is only possible before save).
  • The default width property alias for Umbraco images is umbracoWidth—this is auto-populated when images are uploaded.

内容的提问来源于stack exchange,提问作者luxor37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:04:25