BlobFileService.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using AutoMapper;
  2. using Azure.Storage.Blobs;
  3. using Azure.Storage.Blobs.Models;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.StaticFiles;
  7. using Microsoft.Extensions.Logging;
  8. using MTWorkHR.Application.Models;
  9. using MTWorkHR.Application.Services.Interfaces;
  10. using MTWorkHR.Core.Global;
  11. using System.IO;
  12. using System.Net.Http.Headers;
  13. namespace MTWorkHR.Application.Services
  14. {
  15. public class BlobFileService : IFileService
  16. {
  17. // private readonly AppSettingsConfiguration settings;
  18. private const string ContainerName = "blobcontainer";
  19. public const string SuccessMessageKey = "SuccessMessage";
  20. public const string ErrorMessageKey = "ErrorMessage";
  21. private readonly BlobServiceClient _blobServiceClient;
  22. private readonly BlobContainerClient _containerClient;
  23. private readonly ILogger<BlobFileService> _logger;
  24. public BlobFileService(BlobServiceClient blobServiceClient, ILogger<BlobFileService> logger)
  25. {
  26. _blobServiceClient = blobServiceClient;
  27. _containerClient = _blobServiceClient.GetBlobContainerClient(ContainerName);
  28. _containerClient.CreateIfNotExists();
  29. _logger = logger;
  30. }
  31. public async Task<AttachmentResponseDto> UploadFile(IFormFile file)
  32. {
  33. AttachmentResponseDto result = new AttachmentResponseDto();
  34. try
  35. {
  36. string uniqueFileName = GenerateUniqueFileName(file.FileName);
  37. var blobClient = _containerClient.GetBlobClient(uniqueFileName);
  38. if (blobClient != null)
  39. {
  40. if (blobClient.ExistsAsync().Result)
  41. {
  42. uniqueFileName = GenerateUniqueFileName(file.FileName);
  43. }
  44. var status = await blobClient.UploadAsync(file.OpenReadStream(), true);
  45. result.OriginalName = file.FileName;
  46. result.FileName = uniqueFileName;
  47. result.FilePath = blobClient.Uri.AbsoluteUri;
  48. return result;
  49. }
  50. else
  51. return result;
  52. }
  53. catch (Exception ex)
  54. {
  55. _logger.LogError(ex.Message);
  56. return result;
  57. }
  58. }
  59. public async Task<string> UploadFileCloud(AttachmentDto file)
  60. {
  61. try
  62. {
  63. // Generate a unique file name to avoid overwriting
  64. string uniqueFileName = GenerateUniqueFileName(file.FileName);
  65. var blobClient = _containerClient.GetBlobClient(uniqueFileName);
  66. _logger.LogInformation("0########## File upload start uniqueFileName={0}", uniqueFileName);
  67. if (blobClient != null)
  68. {
  69. if (blobClient.ExistsAsync().Result)
  70. {
  71. uniqueFileName = GenerateUniqueFileName(file.FileName);
  72. }
  73. using (Stream fs = file.FileData.OpenReadStream())
  74. {
  75. // Upload the file to blob storage
  76. await blobClient.UploadAsync(fs, true);
  77. fs.Position = 0;
  78. using (BinaryReader br = new BinaryReader(fs))
  79. {
  80. byte[] bytes = br.ReadBytes((Int32)fs.Length);
  81. var headers = file.FileData.Headers;
  82. file.Content = bytes;
  83. file.ContentType = file.FileData.ContentType;
  84. file.FilePath = blobClient.Uri.AbsoluteUri;
  85. file.OriginalName = file.FileName;
  86. file.FileName = uniqueFileName;
  87. }
  88. }
  89. _logger.LogInformation("1########## File upload finish path={0}", blobClient.Uri.AbsoluteUri);
  90. return blobClient.Uri.AbsoluteUri;
  91. }
  92. else
  93. {
  94. return "";
  95. }
  96. }
  97. catch (Exception ex)
  98. {
  99. _logger.LogError(ex.Message);
  100. return "";
  101. }
  102. }
  103. // Helper method to generate a unique file name
  104. private string GenerateUniqueFileName(string originalFileName)
  105. {
  106. // Extract file name and extension
  107. string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFileName);
  108. string extension = Path.GetExtension(originalFileName);
  109. // Append a unique identifier (e.g., timestamp or GUID)
  110. string uniqueIdentifier = DateTime.UtcNow.Ticks.ToString(); // or Guid.NewGuid().ToString()
  111. return $"{fileNameWithoutExtension}_{uniqueIdentifier}{extension}";
  112. }
  113. public async Task<AttachmentResponseDto> UploadFile(byte[] pdfBytes, string fileName)
  114. {
  115. AttachmentResponseDto result = new AttachmentResponseDto();
  116. try
  117. {
  118. // Get a reference to the container
  119. //BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient("Contracts");
  120. // Create the container if it doesn’t exist
  121. //containerClient.CreateIfNotExists();
  122. var blobClient = _containerClient.GetBlobClient(fileName);
  123. if (blobClient != null)
  124. {
  125. using (MemoryStream uploadStream = new MemoryStream(pdfBytes))
  126. {
  127. _logger.LogInformation("1--Contract uploadStream length={0}", pdfBytes.Length);
  128. var status = await blobClient.UploadAsync(uploadStream, overwrite: true);
  129. _logger.LogInformation("2--Contract uploadStream Status={0}, uri={1}", status, blobClient.Uri.AbsoluteUri);
  130. }
  131. result.FileName = fileName;
  132. result.FilePath = blobClient.Uri.AbsoluteUri;
  133. _logger.LogInformation("3--Contract upload finish path={0}", blobClient.Uri.AbsoluteUri);
  134. return result;
  135. }
  136. else
  137. {
  138. _logger.LogInformation("BlobClient is null when upload file ={0}", fileName);
  139. return result;
  140. }
  141. }
  142. catch (Exception ex)
  143. {
  144. _logger.LogError(ex.Message);
  145. return result;
  146. }
  147. }
  148. public async Task<BlobObject> Download(string url)
  149. {
  150. try
  151. {
  152. var fileName = new Uri(url).Segments.LastOrDefault();
  153. var blobClient = _containerClient.GetBlobClient(fileName);
  154. if(await blobClient.ExistsAsync())
  155. {
  156. BlobDownloadResult content = await blobClient.DownloadContentAsync();
  157. var downloadedData = content.Content.ToStream();
  158. if (ImageExtensions.Contains(Path.GetExtension(fileName.ToUpperInvariant())))
  159. {
  160. var extension = Path.GetExtension(fileName);
  161. return new BlobObject { Content = downloadedData, ContentType = "image/"+extension.Remove(0,1) };
  162. }
  163. else
  164. {
  165. return new BlobObject { Content = downloadedData, ContentType = content.Details.ContentType };
  166. }
  167. }
  168. return null;
  169. }
  170. catch (Exception ex)
  171. {
  172. return null;
  173. }
  174. }
  175. public async Task<List<AttachmentResponseDto>> UploadFiles(List<IFormFile> files)
  176. {
  177. List<AttachmentResponseDto> msgs = new List<AttachmentResponseDto>();
  178. foreach (var formFile in files)
  179. {
  180. msgs.Add(await UploadFile(formFile));
  181. }
  182. return msgs;
  183. }
  184. public async Task<bool> Delete(string fileName)
  185. {
  186. try
  187. {
  188. var blobClient = _containerClient.GetBlobClient(fileName);
  189. await blobClient.DeleteIfExistsAsync();
  190. return true;
  191. }
  192. catch (Exception ex)
  193. {
  194. return false;
  195. }
  196. }
  197. public void CopyFileToCloud(ref List<AttachmentDto> attachments)
  198. {
  199. foreach(var attach in attachments)
  200. {
  201. if (attach.FileData != null)
  202. {
  203. var resPath = UploadFileCloud(attach).Result;
  204. //if (resPath != "")
  205. // attach.FilePath = resPath;
  206. }
  207. }
  208. }
  209. public bool CopyFileToActualFolder(string FileName)
  210. {
  211. throw new NotImplementedException();
  212. }
  213. public bool DeleteFileFromTempFolder(string FileName)
  214. {
  215. throw new NotImplementedException();
  216. }
  217. public string GetTempAttachmentPath()
  218. {
  219. throw new NotImplementedException();
  220. }
  221. public string GetActualAttachmentPath()
  222. {
  223. throw new NotImplementedException();
  224. }
  225. public Task<Tuple<MemoryStream, string, string>> GetFileDownloadInfo(string fileUrl)
  226. {
  227. throw new NotImplementedException();
  228. }
  229. public Task<bool> CopyFileToActualFolder(List<AttachmentDto> attachments)
  230. {
  231. throw new NotImplementedException();
  232. }
  233. string[] ImageExtensions = new string[]
  234. {
  235. ".JPEG"
  236. , ".JPG"
  237. , ".PNG"
  238. };
  239. }
  240. }