StorageHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections;
  6. using System.IO;
  7. using System.Runtime.Serialization.Formatters.Binary;
  8. using System.Data;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.Extensions.Options;
  11. using Microsoft.AspNetCore.Http;
  12. using FMSAdmin.Models;
  13. using FMSAdmin.Entities;
  14. using System.Drawing;
  15. using System.Drawing.Imaging;
  16. using SelectPdf;
  17. namespace FMSAdmin.Helpers {
  18. public class StorageHelper {
  19. private readonly AppSettings _appSettings;
  20. private readonly ILogger<StorageHelper> _logger;
  21. public StorageHelper(
  22. IOptions<AppSettings> appSettings,
  23. ILogger<StorageHelper> logger
  24. ) {
  25. _appSettings = appSettings.Value;
  26. _logger = logger;
  27. var currentDir = _appSettings.StoragePath;
  28. // 초기 디렉토리 생성 - 추후 프로그램 초기화 부분으로..
  29. Directory.CreateDirectory(currentDir + "/wwwroot/files");
  30. Directory.CreateDirectory(currentDir + "/wwwroot/files/temp");
  31. Directory.CreateDirectory(currentDir + "/wwwroot/files/editor");
  32. }
  33. public bool DirectoryExists(string path) {
  34. return Directory.Exists(_LocalPath(path));
  35. }
  36. public bool FileExists(string path) {
  37. return File.Exists(_LocalPath(path));
  38. }
  39. public string ReadAllText(string path) {
  40. return File.ReadAllText(_LocalPath(path));
  41. }
  42. public void WriteAllText(string path, string text) {
  43. File.WriteAllText(_LocalPath(path), text);
  44. }
  45. public void CreateDirectory(string path) {
  46. var localPath = _LocalPath(path);
  47. if (!Directory.Exists(localPath)) {
  48. Directory.CreateDirectory(localPath);
  49. }
  50. }
  51. public UploadFile Save(string path, IFormFile file) {
  52. var filePath = $"{path}";
  53. filePath = filePath.Replace("//", "/");
  54. var localPath = _LocalPath(filePath);
  55. string fullUrl = _FullUrl(filePath);
  56. if (file.Length > 0) {
  57. using (var stream = new FileStream(localPath, FileMode.Create)) {
  58. file.CopyTo(stream);
  59. }
  60. }
  61. return new UploadFile {
  62. Name = file.FileName,
  63. FileSize = file.Length,
  64. ContentType = file.ContentType,
  65. Path = filePath,
  66. Url = fullUrl
  67. };
  68. }
  69. private bool Compress(string path, Stream stream) {
  70. bool isCompress = false;
  71. Image image = null;
  72. try { image = Image.FromStream(stream); } catch { }
  73. if (image != null) {
  74. var jpgEncoder = ImageCodecInfo.GetImageDecoders().Where(x => x.FormatID == ImageFormat.Jpeg.Guid).FirstOrDefault();
  75. if (jpgEncoder != null) {
  76. try {
  77. var encoderParameters = new EncoderParameters(1);
  78. encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);
  79. image.Save(path, jpgEncoder, encoderParameters);
  80. isCompress = true;
  81. } catch { }
  82. }
  83. }
  84. return isCompress;
  85. }
  86. public UploadFile SaveImage(string path, IFormFile file) {
  87. var filePath = $"{path}";
  88. filePath = filePath.Replace("//", "/");
  89. var localPath = _LocalPath(filePath);
  90. string fullUrl = _FullUrl(filePath);
  91. if (file.Length > 0) {
  92. bool isCompress = false;
  93. using (var stream = file.OpenReadStream()) {
  94. isCompress = Compress(localPath, stream);
  95. }
  96. if (!isCompress) {
  97. using (var stream = new FileStream(localPath, FileMode.Create)) {
  98. file.CopyTo(stream);
  99. }
  100. }
  101. }
  102. return new UploadFile {
  103. Name = file.FileName,
  104. FileSize = file.Length,
  105. ContentType = file.ContentType,
  106. Path = filePath,
  107. Url = fullUrl
  108. };
  109. }
  110. public void Copy(string src, string dst) {
  111. var srcPath = _LocalPath(src);
  112. var dstPath = _LocalPath(dst);
  113. _logger.LogInformation("copy " + srcPath + " to " + dstPath);
  114. File.Copy(srcPath, dstPath, true);
  115. }
  116. public void Move(string src, string dst) {
  117. var srcPath = _LocalPath(src);
  118. var dstPath = _LocalPath(dst);
  119. _logger.LogInformation("move " + srcPath + " to " + dstPath);
  120. File.Move(srcPath, dstPath, true);
  121. }
  122. public void DeleteTempFiles(double oldDay = 1) {
  123. var tempDir = _LocalPath("/temp");
  124. // 파일
  125. foreach (var file in Directory.GetFiles(tempDir)) {
  126. var created = File.GetCreationTime(file);
  127. if ((DateTime.Now - created).TotalDays > oldDay) {
  128. File.Delete(file);
  129. //_logger.LogInformation("delete file " + file);
  130. }
  131. }
  132. // 폴더
  133. foreach (var dir in Directory.GetDirectories(tempDir)) {
  134. var created = Directory.GetCreationTime(dir);
  135. if ((DateTime.Now - created).TotalDays > oldDay) {
  136. Directory.Delete(dir, true);
  137. //_logger.LogInformation("delete directory " + dir);
  138. }
  139. }
  140. }
  141. public UploadFile SaveTemp(IFormFile file) {
  142. var ext = Path.GetExtension(file.FileName);
  143. var name = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
  144. var filename = $"{name}{ext}";
  145. return Save($"/temp/{filename}", file);
  146. }
  147. public UploadFile SaveTempImage(IFormFile file) {
  148. var ext = Path.GetExtension(file.FileName);
  149. var name = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
  150. var filename = $"{name}{ext}";
  151. return SaveImage($"/temp/{filename}", file);
  152. }
  153. public void CopyEntity(string temp, CmFile file) {
  154. if (file == null) return;
  155. if (file.FileCategory == null) return;
  156. var entity = file.FileCategoryId;
  157. var ext = Path.GetExtension(file.Name);
  158. var filename = $"{file.FileId}{ext}";
  159. var currentDir = _appSettings.StoragePath;
  160. Directory.CreateDirectory(currentDir + "/wwwroot/files/" + entity);
  161. Copy(temp, $"/{entity}/{filename}");
  162. }
  163. public object ParseFile(CmFile file) {
  164. if (file == null) return null;
  165. var ext = Path.GetExtension(file.Name);
  166. file.Path = $"/{file.FileCategoryId}/{file.FileId}{ext}";
  167. file.Url = _FullUrl(file.Path);
  168. return new {
  169. file.FileId,
  170. file.Name,
  171. file.FileCategoryId,
  172. file.FileSize,
  173. file.ContentType,
  174. file.Path,
  175. file.Url,
  176. };
  177. }
  178. public string ParseFileUrl(CmFile file) {
  179. if (file == null) return null;
  180. var ext = Path.GetExtension(file.Name);
  181. file.Path = $"/{file.FileCategoryId}/{file.FileId}{ext}";
  182. file.Url = _FullUrl(file.Path);
  183. return file.Url;
  184. }
  185. public string getFilePath(CmFile file) {
  186. if (file == null) return null;
  187. var ext = Path.GetExtension(file.Name);
  188. return $"/{file.FileCategoryId}/{file.FileId}{ext}";
  189. }
  190. public void CopyGroup(string temp, string group, string file) {
  191. if (string.IsNullOrEmpty(group)) return;
  192. if (string.IsNullOrEmpty(file)) return;
  193. group = group.ToLower();
  194. CreateDirectory("/" + group);
  195. Copy(temp, $"/{group}/{file}");
  196. }
  197. public FileStream GetFileStream(string path) {
  198. return File.OpenRead(_LocalPath(path));
  199. }
  200. public String GetLocalPath(string path) {
  201. return _LocalPath(path);
  202. }
  203. public String GetFullUrl(string path) {
  204. return _FullUrl(path);
  205. }
  206. private string _LocalPath(string path) {
  207. var currentDir = _appSettings.StoragePath;
  208. var basePath = "/files";
  209. var filePath = $"{path}";
  210. filePath = filePath.Replace("//", "/");
  211. var localPath = $"{currentDir}/wwwroot/{basePath}/{filePath}";
  212. localPath = localPath.Replace("//", "/");
  213. return localPath;
  214. }
  215. private string _FullUrl(string path) {
  216. var basePath = "/files";
  217. string fullUrl = $"{_appSettings.StorageUrl}{basePath}{path}";
  218. return fullUrl;
  219. }
  220. public void PdfConvertImage(CmFile pdf) {
  221. var ext = Path.GetExtension(pdf.Name);
  222. if (ext == ".pdf") {
  223. SelectPdf.GlobalProperties.LicenseKey = "nrWvvqyrr76nqKq+rK6wrr6tr7CvrLCnp6en";
  224. PdfRasterizer rasterizer = new PdfRasterizer();
  225. rasterizer.Load(GetLocalPath(pdf.Path));
  226. rasterizer.Resolution = 300;
  227. rasterizer.ColorSpace = PdfRasterizerColorSpace.RGB;
  228. System.Drawing.Image[] images = rasterizer.ConvertToImages();
  229. var p = 1;
  230. var currentDir = _appSettings.StoragePath;
  231. CreateDirectory("/pdf_images/" + pdf.FileId);
  232. foreach (var file in Directory.GetFiles(currentDir + "/wwwroot/files/pdf_images/" + pdf.FileId)) {
  233. File.Delete(file);
  234. }
  235. foreach (var image in images) {
  236. var file = $"/pdf_images/{pdf.FileId}/SavePageCustomResolution_{p}.png";
  237. var url = GetFullUrl(file);
  238. image.Save(GetLocalPath(file));
  239. p++;
  240. }
  241. } else {
  242. throw new Exception("PDF 파일만 등록 가능합니다.");
  243. }
  244. }
  245. public ArrayList GetPdfImages(CmFile pdf) {
  246. ArrayList files = new ArrayList();
  247. var currentDir = _appSettings.StoragePath;
  248. if (pdf != null)
  249. if (Directory.Exists(currentDir + "/wwwroot/files/pdf_images/" + pdf.FileId)) {
  250. foreach (var file in Directory.GetFiles(currentDir + "/wwwroot/files/pdf_images/" + pdf.FileId)) {
  251. files.Add(_FullUrl("/pdf_images/" + pdf.FileId + "/" + Path.GetFileName(file)));
  252. }
  253. }
  254. return files;
  255. }
  256. }
  257. }