LocalFileStorage.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Logging;
  4. using SharedKernel.Storage;
  5. namespace Infrastructure.Storage
  6. {
  7. public sealed class LocalFileStorage : IFileStorage
  8. {
  9. private readonly IWebHostEnvironment _env;
  10. private readonly ILogger<LocalFileStorage> _log;
  11. public LocalFileStorage(IWebHostEnvironment env, ILogger<LocalFileStorage> log)
  12. {
  13. _env = env;
  14. _log = log;
  15. }
  16. public async Task<FileUploadResult?> SaveFileAsync(IFormFile? file, FileStoragePath path, string[] allowedExtensions, CancellationToken ct = default)
  17. {
  18. if (file is null || file.Length <= 0)
  19. {
  20. return null;
  21. }
  22. var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
  23. if (!allowedExtensions.Contains(ext))
  24. {
  25. throw new ArgumentException("허용되지 않는 파일 확장자입니다.");
  26. }
  27. var rel = path.ToRelativePath();
  28. var dir = CombineUnderWebRoot(rel);
  29. Directory.CreateDirectory(dir); // 경로 생성(없으면)
  30. var fileName = $"{Guid.NewGuid():N}{ext}";
  31. var fullPath = Path.Combine(dir, fileName);
  32. await using var fs = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
  33. await file.CopyToAsync(fs, ct);
  34. var url = "/" + $"{rel}/{fileName}".Replace("\\", "/");
  35. short? width = null, height = null;
  36. if (IsImageExtension(ext))
  37. {
  38. using var readStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
  39. var dim = ImageDimensionHelper.GetDimensions(readStream);
  40. if (dim.HasValue)
  41. {
  42. width = dim.Value.Width;
  43. height = dim.Value.Height;
  44. }
  45. }
  46. return new FileUploadResult(url, fileName, file.Length, ext, width, height);
  47. }
  48. public async Task<FileUploadResult?> SaveBytesAsync(ReadOnlyMemory<byte> bytes, string extension, FileStoragePath path, CancellationToken ct = default)
  49. {
  50. if (bytes.Length <= 0)
  51. {
  52. return null;
  53. }
  54. var ext = FileUtils.NormalizeExtension(extension);
  55. if (ext is not (".jpg" or ".png" or ".gif" or ".bmp" or ".webp"))
  56. {
  57. throw new ArgumentException("허용되지 않는 파일 확장자입니다.");
  58. }
  59. var rel = path.ToRelativePath();
  60. var dir = CombineUnderWebRoot(rel);
  61. Directory.CreateDirectory(dir); // 경로 생성(없으면)
  62. var fileName = $"{Guid.NewGuid():N}{ext}";
  63. var fullPath = Path.Combine(dir, fileName);
  64. await File.WriteAllBytesAsync(fullPath, bytes.ToArray(), ct);
  65. var url = "/" + $"{rel}/{fileName}".Replace("\\", "/");
  66. short? width = null, height = null;
  67. var dim = ImageDimensionHelper.GetDimensions(bytes);
  68. if (dim.HasValue)
  69. {
  70. width = dim.Value.Width;
  71. height = dim.Value.Height;
  72. }
  73. return new FileUploadResult(url, fileName, bytes.Length, ext, width, height);
  74. }
  75. public void DeleteByUrl(string? url)
  76. {
  77. if (string.IsNullOrWhiteSpace(url))
  78. {
  79. return;
  80. }
  81. if (!FileUtils.IsLocalPublicUrl(url))
  82. {
  83. _log.LogWarning("삭제가 불가한 주소입니다. {0}", url);
  84. return;
  85. }
  86. var fullPath = CombineUnderWebRoot(url.TrimStart('/'));
  87. if (!File.Exists(fullPath))
  88. {
  89. _log.LogWarning("파일을 찾을 수 없습니다. {0}", fullPath);
  90. return;
  91. }
  92. try
  93. {
  94. File.Delete(fullPath);
  95. _log.LogInformation("파일이 삭제됨 : {0}", fullPath);
  96. }
  97. catch (Exception e)
  98. {
  99. _log.LogError(e, "파일 삭제 중 오류가 발생했습니다. {0}", fullPath);
  100. }
  101. }
  102. private static bool IsImageExtension(string ext)
  103. {
  104. return ext is ".jpg" or ".jpeg" or ".png" or ".gif" or ".webp" or ".bmp";
  105. }
  106. private string CombineUnderWebRoot(string relative)
  107. {
  108. var webRoot = Path.GetFullPath(_env.WebRootPath);
  109. var fullPath = Path.GetFullPath(Path.Combine(_env.WebRootPath, relative));
  110. if (!fullPath.StartsWith(webRoot, StringComparison.OrdinalIgnoreCase))
  111. {
  112. throw new UnauthorizedAccessException("경로를 찾을 수 없습니다.");
  113. }
  114. return fullPath;
  115. }
  116. }
  117. }