LocalFileStorage.cs 4.8 KB

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