FileService.cs 7.3 KB

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