| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- using static NuGet.Packaging.PackagingConstants;
- namespace bitforum.Services
- {
- public enum UploadFolder
- {
- Document,
- Faq,
- Popup,
- Banner
- }
- public interface IFileUploadService
- {
- Task<string> UploadImageAsync(IFormFile file, UploadFolder folor);
- Task<string> UploadFileAsync(IFormFile file, string[] allowedExtensions, UploadFolder folor);
- }
- public class FileUploadService : IFileUploadService
- {
- private readonly IWebHostEnvironment _environment;
- public FileUploadService(IWebHostEnvironment environment)
- {
- _environment = environment;
- }
- // 이미지 저장
- public async Task<string?> UploadImageAsync(IFormFile? file, UploadFolder folor)
- {
- return await UploadFileAsync(file, [".jpg", ".jpeg", ".png", ".gif"], folor);
- }
- // 파일 저장
- public async Task<string?> 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;
- }
- }
- }
|