FileUploadService.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using static NuGet.Packaging.PackagingConstants;
  2. namespace bitforum.Services
  3. {
  4. public enum UploadFolder
  5. {
  6. Document,
  7. Faq,
  8. Popup,
  9. Banner
  10. }
  11. public interface IFileUploadService
  12. {
  13. Task<string> UploadImageAsync(IFormFile file, UploadFolder folor);
  14. Task<string> UploadFileAsync(IFormFile file, string[] allowedExtensions, UploadFolder folor);
  15. }
  16. public class FileUploadService : IFileUploadService
  17. {
  18. private readonly IWebHostEnvironment _environment;
  19. public FileUploadService(IWebHostEnvironment environment)
  20. {
  21. _environment = environment;
  22. }
  23. // 이미지 저장
  24. public async Task<string?> UploadImageAsync(IFormFile? file, UploadFolder folor)
  25. {
  26. return await UploadFileAsync(file, [".jpg", ".jpeg", ".png", ".gif"], folor);
  27. }
  28. // 파일 저장
  29. public async Task<string?> UploadFileAsync(IFormFile? file, string[] allowedExtensions, UploadFolder folder)
  30. {
  31. if (file == null || file.Length == 0)
  32. {
  33. return null;
  34. }
  35. var extension = Path.GetExtension(file.FileName).ToLower();
  36. if (!Array.Exists(allowedExtensions, ext => ext == extension))
  37. {
  38. throw new ArgumentException("허용되지 않는 파일 형식입니다.");
  39. }
  40. string uploadFolder = folder switch
  41. {
  42. UploadFolder.Document => "editor/images",
  43. UploadFolder.Faq => "editor/faq",
  44. UploadFolder.Popup => "editor/popup",
  45. UploadFolder.Banner => "upload/banner",
  46. _ => throw new ArgumentException("유효하지 않은 경로입니다.")
  47. };
  48. var uploadPath = Path.Combine(_environment.WebRootPath, uploadFolder);
  49. if (!Directory.Exists(uploadPath))
  50. {
  51. Directory.CreateDirectory(uploadPath);
  52. }
  53. var uniqueFileName = $"{Guid.NewGuid()}{extension}";
  54. var filePath = Path.Combine(uploadPath, uniqueFileName);
  55. using (var stream = new FileStream(filePath, FileMode.Create))
  56. {
  57. await file.CopyToAsync(stream);
  58. }
  59. return $"/{uploadFolder}/{uniqueFileName}";
  60. }
  61. // 파일 삭제
  62. public bool RemoveFile(string? filePath)
  63. {
  64. if (string.IsNullOrEmpty(filePath))
  65. {
  66. return false;
  67. }
  68. var fullPath = Path.Combine(_environment.WebRootPath, filePath.TrimStart('/'));
  69. if (File.Exists(fullPath))
  70. {
  71. File.Delete(fullPath);
  72. return true;
  73. }
  74. return false;
  75. }
  76. }
  77. }