FileService.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 bool CopyFileToActualFolder(List<AttachmentDto> attachments)
  72. {
  73. foreach (var attachment in attachments)
  74. {
  75. if (!Directory.Exists(GetActualAttachmentPath()))
  76. Directory.CreateDirectory(GetActualAttachmentPath());
  77. var tempFilePath = Path.Combine(GetTempAttachmentPath(), attachment.FileName);
  78. var destinationFilePath = Path.Combine(GetActualAttachmentPath(), attachment.FileName);
  79. if (File.Exists(tempFilePath))
  80. {
  81. if (!File.Exists(destinationFilePath))
  82. File.Copy(tempFilePath, destinationFilePath);
  83. }
  84. else
  85. return false;
  86. }
  87. return true;
  88. }
  89. public bool CopyFileToActualFolder(string FileName)
  90. {
  91. if (!Directory.Exists(GetActualAttachmentPath()))
  92. Directory.CreateDirectory(GetActualAttachmentPath());
  93. var tempFilePath = Path.Combine(GetTempAttachmentPath(), FileName);
  94. var destinationFilePath = Path.Combine(GetActualAttachmentPath(), FileName);
  95. if (File.Exists(tempFilePath))
  96. {
  97. if (!File.Exists(destinationFilePath))
  98. File.Copy(tempFilePath, destinationFilePath);
  99. return true;
  100. }
  101. return false;
  102. }
  103. public bool DeleteFileFromTempFolder(string FileName)
  104. {
  105. try
  106. {
  107. string pathToRemove = GetTempAttachmentPath();
  108. if (Directory.Exists(pathToRemove))
  109. {
  110. var tempFilePath = Path.Combine(pathToRemove, FileName);
  111. if (File.Exists(tempFilePath))
  112. {
  113. File.Delete(tempFilePath);
  114. }
  115. }
  116. }
  117. catch (Exception ex) { }
  118. return true;
  119. }
  120. public string GetTempAttachmentPath()
  121. {
  122. var pathTemp = settings.AttachmentSettings.TempAttachment;
  123. return pathTemp;
  124. }
  125. public string GetActualAttachmentPath()
  126. {
  127. var pathActual = settings.AttachmentSettings.ActualAttachment ;
  128. return pathActual;
  129. }
  130. private bool AttachmentsMust(List<IFormFile> files)
  131. {
  132. // extensions whitelist
  133. string[] allowedExtensions = new string[]
  134. {
  135. ".jpeg"
  136. , ".jpg"
  137. , ".png"
  138. , ".pdf"
  139. , ".doc"
  140. , ".docx"
  141. , ".csv"
  142. , ".xls"
  143. , ".xlsx"
  144. , ".txt"
  145. , ".pptx"
  146. , ".svg"
  147. , ".webp"
  148. };
  149. // MIME types whitelist
  150. string[] allowedMIMETypes = new string[]
  151. {
  152. "image/jpeg"
  153. , "image/png"
  154. , "application/pdf"
  155. , "application/msword"
  156. , "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  157. , "text/csv"
  158. , "application/vnd.ms-excel"
  159. , "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  160. , "text/plain"
  161. , "application/vnd.openxmlformats-officedocument.presentationml.presentation"
  162. , "image/svg+xml"
  163. , "image/webp"
  164. };
  165. foreach (IFormFile file in files)
  166. {
  167. if (!allowedExtensions.Contains(Path.GetExtension(file.FileName).ToLower()))
  168. return false;
  169. if (!allowedMIMETypes.Contains(file.ContentType.ToLower()))
  170. return false;
  171. }
  172. return true;
  173. }
  174. }
  175. }