FileService.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. using AutoMapper;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.StaticFiles;
  4. using MTWorkHR.Application.Models;
  5. using MTWorkHR.Application.Services.Interfaces;
  6. using MTWorkHR.Core.Global;
  7. using System.Net.Http.Headers;
  8. namespace MTWorkHR.Application.Services
  9. {
  10. public class FileService : IFileService
  11. {
  12. private readonly AppSettingsConfiguration settings;
  13. public FileService(AppSettingsConfiguration settings)
  14. {
  15. this.settings = settings;
  16. }
  17. public string UploadFile(IFormFile file)
  18. {
  19. return UploadFiles(new List<IFormFile> { file }).First();
  20. }
  21. public List<string> UploadFiles(List<IFormFile> files)
  22. {
  23. if (!AttachmentsMust(files))
  24. throw new AppException(ExceptionEnum.InvalidFileType);
  25. string pathToSave = GetTempAttachmentPath();
  26. if (!Directory.Exists(pathToSave))
  27. Directory.CreateDirectory(pathToSave);
  28. var fileNames = new List<string>();
  29. foreach (var formFile in files)
  30. {
  31. var fname = ContentDispositionHeaderValue.Parse(formFile.ContentDisposition).FileName.Trim('"');
  32. var fnameSplit = fname.Split(".");
  33. var fNewName = Guid.NewGuid().ToString() + "." + fnameSplit[fnameSplit.Length - 1];
  34. var fullPath = Path.Combine(pathToSave, fNewName);
  35. fileNames.Add(fNewName);
  36. if (formFile.Length > 0)
  37. {
  38. using (var stream = new FileStream(fullPath, FileMode.Create))
  39. {
  40. formFile.CopyToAsync(stream);
  41. }
  42. }
  43. else
  44. throw new AppException(ExceptionEnum.FileLengthNotCorrect);
  45. }
  46. return fileNames;
  47. }
  48. public async Task<Tuple<MemoryStream,string, string>> GetFileDownloadInfo(string fileUrl)
  49. {
  50. var filePath = Path.Combine(GetActualAttachmentPath(), fileUrl);
  51. if (!System.IO.File.Exists(filePath))
  52. throw new AppException(ExceptionEnum.RecordNotExist);
  53. var memory = new MemoryStream();
  54. await using (var stream = new FileStream(filePath, FileMode.Open))
  55. {
  56. await stream.CopyToAsync(memory);
  57. }
  58. memory.Position = 0;
  59. return new Tuple<MemoryStream, string, string>(memory, GetContentType(filePath), filePath);
  60. }
  61. private string GetContentType(string path)
  62. {
  63. var provider = new FileExtensionContentTypeProvider();
  64. string contentType;
  65. if (!provider.TryGetContentType(path, out contentType))
  66. {
  67. contentType = "application/octet-stream";
  68. }
  69. return contentType;
  70. }
  71. public async Task<bool> CopyFileToActualFolder(List<AttachmentDto> attachments)
  72. {
  73. foreach (var attachment in attachments)
  74. {
  75. var files = attachments.Select(a => a.FileData);
  76. foreach (var formFile in files)
  77. {
  78. if (formFile.Length > 0)
  79. {
  80. var filePath = Path.GetTempFileName();
  81. using (var stream = System.IO.File.Create(filePath))
  82. {
  83. await formFile.CopyToAsync(stream);
  84. }
  85. }
  86. }
  87. if (!Directory.Exists(GetActualAttachmentPath()))
  88. Directory.CreateDirectory(GetActualAttachmentPath());
  89. var tempFilePath = Path.Combine(GetTempAttachmentPath(), attachment.FileName);
  90. var destinationFilePath = Path.Combine(GetActualAttachmentPath(), attachment.FileName);
  91. if (File.Exists(tempFilePath))
  92. {
  93. if (!File.Exists(destinationFilePath))
  94. File.Copy(tempFilePath, destinationFilePath);
  95. }
  96. else
  97. return false;
  98. }
  99. return true;
  100. }
  101. public bool CopyFileToActualFolder(string FileName)
  102. {
  103. if (!Directory.Exists(GetActualAttachmentPath()))
  104. Directory.CreateDirectory(GetActualAttachmentPath());
  105. var tempFilePath = Path.Combine(GetTempAttachmentPath(), FileName);
  106. var destinationFilePath = Path.Combine(GetActualAttachmentPath(), FileName);
  107. if (File.Exists(tempFilePath))
  108. {
  109. if (!File.Exists(destinationFilePath))
  110. File.Copy(tempFilePath, destinationFilePath);
  111. return true;
  112. }
  113. return false;
  114. }
  115. public bool DeleteFileFromTempFolder(string FileName)
  116. {
  117. try
  118. {
  119. string pathToRemove = GetTempAttachmentPath();
  120. if (Directory.Exists(pathToRemove))
  121. {
  122. var tempFilePath = Path.Combine(pathToRemove, FileName);
  123. if (File.Exists(tempFilePath))
  124. {
  125. File.Delete(tempFilePath);
  126. }
  127. }
  128. }
  129. catch (Exception ex) { }
  130. return true;
  131. }
  132. public string GetTempAttachmentPath()
  133. {
  134. var pathTemp = settings.AttachmentSettings.TempAttachment;
  135. return pathTemp;
  136. }
  137. public string GetActualAttachmentPath()
  138. {
  139. var pathActual = settings.AttachmentSettings.ActualAttachment ;
  140. return pathActual;
  141. }
  142. private bool AttachmentsMust(List<IFormFile> files)
  143. {
  144. // extensions whitelist
  145. string[] allowedExtensions = new string[]
  146. {
  147. ".jpeg"
  148. , ".jpg"
  149. , ".png"
  150. , ".pdf"
  151. , ".doc"
  152. , ".docx"
  153. , ".csv"
  154. , ".xls"
  155. , ".xlsx"
  156. , ".txt"
  157. , ".pptx"
  158. , ".svg"
  159. , ".webp"
  160. };
  161. // MIME types whitelist
  162. string[] allowedMIMETypes = new string[]
  163. {
  164. "image/jpeg"
  165. , "image/png"
  166. , "application/pdf"
  167. , "application/msword"
  168. , "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  169. , "text/csv"
  170. , "application/vnd.ms-excel"
  171. , "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  172. , "text/plain"
  173. , "application/vnd.openxmlformats-officedocument.presentationml.presentation"
  174. , "image/svg+xml"
  175. , "image/webp"
  176. };
  177. foreach (IFormFile file in files)
  178. {
  179. if (!allowedExtensions.Contains(Path.GetExtension(file.FileName).ToLower()))
  180. return false;
  181. if (!allowedMIMETypes.Contains(file.ContentType.ToLower()))
  182. return false;
  183. }
  184. return true;
  185. }
  186. }
  187. }