LSTANCZYK
9/25/2017 - 1:30 AM

File max size validation attribute for ASP.NET MVC

File max size validation attribute for ASP.NET MVC

namespace App.Infrastructure
{
    public class FileMaxSizeAttribute : ValidationAttribute
    {
        public FileMaxSizeAttribute(int maxSize = 10 * 1024 * 1024, string errorMessage = "{0} is not a valid file.")
            : base(errorMessage)
        {
            // 10 MB by default //
            this._maxSize = maxSize;
        }
    
        public override ValidationResult IsValid(object value, ValidationContext context)
        {
            var file = value as HttpPostedFileBase;
    
            if (file == null || file.ContentLength > _maxSize)
            {
                return new ValidationResult(FormatErrorMessage(context.DisplayName));
            }
    
            return ValidationResult.Success;
        }
    
        private readonly float _maxSize;
    }
}