MaxFileSizeAttribute.cs 1.1 KB

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