LocalFileStorage.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. {
  34. await file.CopyToAsync(fs, ct);
  35. }
  36. var url = "/" + $"{rel}/{fileName}".Replace("\\", "/");
  37. short? width = null, height = null;
  38. if (IsImageExtension(ext))
  39. {
  40. using var readStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Read);
  41. var dim = ImageDimensionHelper.GetDimensions(readStream);
  42. if (dim.HasValue)
  43. {
  44. width = dim.Value.Width;
  45. height = dim.Value.Height;
  46. }
  47. }
  48. return new FileUploadResult(url, fileName, file.Length, ext, width, height);
  49. }
  50. public async Task<FileUploadResult?> SaveBytesAsync(ReadOnlyMemory<byte> bytes, string extension, FileStoragePath path, CancellationToken ct = default)
  51. {
  52. if (bytes.Length <= 0)
  53. {
  54. return null;
  55. }
  56. var ext = FileUtils.NormalizeExtension(extension);
  57. if (ext is not (".jpg" or ".png" or ".gif" or ".bmp" or ".webp"))
  58. {
  59. throw new ArgumentException("허용되지 않는 파일 확장자입니다.");
  60. }
  61. var rel = path.ToRelativePath();
  62. var dir = CombineUnderWebRoot(rel);
  63. Directory.CreateDirectory(dir); // 경로 생성(없으면)
  64. var fileName = $"{Guid.NewGuid():N}{ext}";
  65. var fullPath = Path.Combine(dir, fileName);
  66. await File.WriteAllBytesAsync(fullPath, bytes.ToArray(), ct);
  67. var url = "/" + $"{rel}/{fileName}".Replace("\\", "/");
  68. short? width = null, height = null;
  69. var dim = ImageDimensionHelper.GetDimensions(bytes);
  70. if (dim.HasValue)
  71. {
  72. width = dim.Value.Width;
  73. height = dim.Value.Height;
  74. }
  75. return new FileUploadResult(url, fileName, bytes.Length, ext, width, height);
  76. }
  77. public void DeleteByUrl(string? url)
  78. {
  79. if (string.IsNullOrWhiteSpace(url))
  80. {
  81. return;
  82. }
  83. if (!FileUtils.IsLocalPublicUrl(url))
  84. {
  85. _log.LogWarning("삭제가 불가한 주소입니다. {0}", url);
  86. return;
  87. }
  88. var fullPath = CombineUnderWebRoot(url.TrimStart('/'));
  89. if (!File.Exists(fullPath))
  90. {
  91. _log.LogWarning("파일을 찾을 수 없습니다. {0}", fullPath);
  92. return;
  93. }
  94. try
  95. {
  96. File.Delete(fullPath);
  97. _log.LogInformation("파일이 삭제됨 : {0}", fullPath);
  98. }
  99. catch (Exception e)
  100. {
  101. _log.LogError(e, "파일 삭제 중 오류가 발생했습니다. {0}", fullPath);
  102. }
  103. }
  104. private static bool IsImageExtension(string ext)
  105. {
  106. return ext is ".jpg" or ".jpeg" or ".png" or ".gif" or ".webp" or ".bmp";
  107. }
  108. private string CombineUnderWebRoot(string relative)
  109. {
  110. var webRoot = Path.GetFullPath(_env.WebRootPath);
  111. var fullPath = Path.GetFullPath(Path.Combine(_env.WebRootPath, relative));
  112. if (!fullPath.StartsWith(webRoot, StringComparison.OrdinalIgnoreCase))
  113. {
  114. throw new UnauthorizedAccessException("경로를 찾을 수 없습니다.");
  115. }
  116. return fullPath;
  117. }
  118. }
  119. }