MaxFileSizeAttribute.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using Microsoft.AspNetCore.Http;
  2. using System.Collections;
  3. using System.ComponentModel.DataAnnotations;
  4. namespace SharedKernel.Attributes;
  5. /*
  6. * 파일 크기 제한
  7. */
  8. [AttributeUsage(AttributeTargets.Property)]
  9. public class MaxFileSizeAttribute : ValidationAttribute
  10. {
  11. private readonly long _maxKBytes;
  12. public MaxFileSizeAttribute(long maxKBytes)
  13. {
  14. _maxKBytes = maxKBytes;
  15. }
  16. public override bool IsValid(object? value)
  17. {
  18. if (value is IEnumerable files)
  19. {
  20. foreach (var obj in files)
  21. {
  22. if (obj is IFormFile file && file.Length > _maxKBytes)
  23. {
  24. return false;
  25. }
  26. }
  27. }
  28. return true;
  29. }
  30. public override string FormatErrorMessage(string name)
  31. {
  32. var template = string.IsNullOrWhiteSpace(ErrorMessage) ? "{0}의 크기는 최대 {1:N0}KB까지 허용됩니다." : ErrorMessage;
  33. return string.Format(template, name, _maxKBytes);
  34. }
  35. }