using static NuGet.Packaging.PackagingConstants; namespace bitforum.Services { public enum UploadFolder { Document, Faq, Popup, Banner } public interface IFileUploadService { Task UploadImageAsync(IFormFile file, UploadFolder folor); Task UploadFileAsync(IFormFile file, string[] allowedExtensions, UploadFolder folor); } public class FileUploadService : IFileUploadService { private readonly IWebHostEnvironment _environment; public FileUploadService(IWebHostEnvironment environment) { _environment = environment; } // 이미지 저장 public async Task UploadImageAsync(IFormFile? file, UploadFolder folor) { return await UploadFileAsync(file, [".jpg", ".jpeg", ".png", ".gif"], folor); } // 파일 저장 public async Task UploadFileAsync(IFormFile? file, string[] allowedExtensions, UploadFolder folder) { if (file == null || file.Length == 0) { return null; } var extension = Path.GetExtension(file.FileName).ToLower(); if (!Array.Exists(allowedExtensions, ext => ext == extension)) { throw new ArgumentException("허용되지 않는 파일 형식입니다."); } string uploadFolder = folder switch { UploadFolder.Document => "editor/images", UploadFolder.Faq => "editor/faq", UploadFolder.Popup => "editor/popup", UploadFolder.Banner => "upload/banner", _ => throw new ArgumentException("유효하지 않은 경로입니다.") }; var uploadPath = Path.Combine(_environment.WebRootPath, uploadFolder); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } var uniqueFileName = $"{Guid.NewGuid()}{extension}"; var filePath = Path.Combine(uploadPath, uniqueFileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } return $"/{uploadFolder}/{uniqueFileName}"; } // 파일 삭제 public bool RemoveFile(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return false; } var fullPath = Path.Combine(_environment.WebRootPath, filePath.TrimStart('/')); if (File.Exists(fullPath)) { File.Delete(fullPath); return true; } return false; } } }