BlobFileService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. if (blobClient != null)
  67. {
  68. if (blobClient.ExistsAsync().Result)
  69. {
  70. uniqueFileName = GenerateUniqueFileName(file.FileName);
  71. }
  72. using (Stream fs = file.FileData.OpenReadStream())
  73. {
  74. // Upload the file to blob storage
  75. await blobClient.UploadAsync(fs, true);
  76. fs.Position = 0;
  77. using (BinaryReader br = new BinaryReader(fs))
  78. {
  79. byte[] bytes = br.ReadBytes((Int32)fs.Length);
  80. var headers = file.FileData.Headers;
  81. file.Content = bytes;
  82. file.ContentType = file.FileData.ContentType;
  83. file.FilePath = blobClient.Uri.AbsoluteUri;
  84. file.OriginalName = file.FileName;
  85. file.FileName = uniqueFileName;
  86. }
  87. }
  88. return blobClient.Uri.AbsoluteUri;
  89. }
  90. else
  91. {
  92. return "";
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. _logger.LogError(ex.Message);
  98. return "";
  99. }
  100. }
  101. // Helper method to generate a unique file name
  102. private string GenerateUniqueFileName(string originalFileName)
  103. {
  104. // Extract file name and extension
  105. string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFileName);
  106. string extension = Path.GetExtension(originalFileName);
  107. // Append a unique identifier (e.g., timestamp or GUID)
  108. string uniqueIdentifier = DateTime.UtcNow.Ticks.ToString(); // or Guid.NewGuid().ToString()
  109. return $"{fileNameWithoutExtension}_{uniqueIdentifier}{extension}";
  110. }
  111. public async Task<AttachmentResponseDto> UploadFile(byte[] pdfBytes, string fileName)
  112. {
  113. AttachmentResponseDto result = new AttachmentResponseDto();
  114. try
  115. {
  116. // Get a reference to the container
  117. //BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient("Contracts");
  118. // Create the container if it doesn’t exist
  119. //containerClient.CreateIfNotExists();
  120. var blobClient = _containerClient.GetBlobClient(fileName);
  121. if (blobClient != null)
  122. {
  123. using (MemoryStream uploadStream = new MemoryStream(pdfBytes))
  124. {
  125. _logger.LogInformation("1--Contract uploadStream length={0}", pdfBytes.Length);
  126. var status = await blobClient.UploadAsync(uploadStream, overwrite: true);
  127. _logger.LogInformation("2--Contract uploadStream Status={0}, uri={1}", status, blobClient.Uri.AbsoluteUri);
  128. }
  129. result.FileName = fileName;
  130. result.FilePath = blobClient.Uri.AbsoluteUri;
  131. _logger.LogInformation("3--Contract upload finish path={0}", blobClient.Uri.AbsoluteUri);
  132. return result;
  133. }
  134. else
  135. {
  136. _logger.LogInformation("BlobClient is null when upload file ={0}", fileName);
  137. return result;
  138. }
  139. }
  140. catch (Exception ex)
  141. {
  142. _logger.LogError(ex.Message);
  143. return result;
  144. }
  145. }
  146. public async Task<BlobObject> Download(string url)
  147. {
  148. try
  149. {
  150. var fileName = new Uri(url).Segments.LastOrDefault();
  151. var blobClient = _containerClient.GetBlobClient(fileName);
  152. if(await blobClient.ExistsAsync())
  153. {
  154. BlobDownloadResult content = await blobClient.DownloadContentAsync();
  155. var downloadedData = content.Content.ToStream();
  156. if (ImageExtensions.Contains(Path.GetExtension(fileName.ToUpperInvariant())))
  157. {
  158. var extension = Path.GetExtension(fileName);
  159. return new BlobObject { Content = downloadedData, ContentType = "image/"+extension.Remove(0,1) };
  160. }
  161. else
  162. {
  163. return new BlobObject { Content = downloadedData, ContentType = content.Details.ContentType };
  164. }
  165. }
  166. return null;
  167. }
  168. catch (Exception ex)
  169. {
  170. return null;
  171. }
  172. }
  173. public async Task<List<AttachmentResponseDto>> UploadFiles(List<IFormFile> files)
  174. {
  175. List<AttachmentResponseDto> msgs = new List<AttachmentResponseDto>();
  176. foreach (var formFile in files)
  177. {
  178. msgs.Add(await UploadFile(formFile));
  179. }
  180. return msgs;
  181. }
  182. public async Task<bool> Delete(string fileName)
  183. {
  184. try
  185. {
  186. var blobClient = _containerClient.GetBlobClient(fileName);
  187. await blobClient.DeleteIfExistsAsync();
  188. return true;
  189. }
  190. catch (Exception ex)
  191. {
  192. return false;
  193. }
  194. }
  195. public void CopyFileToCloud(ref List<AttachmentDto> attachments)
  196. {
  197. foreach(var attach in attachments)
  198. {
  199. if (attach.FileData != null)
  200. {
  201. var resPath = UploadFileCloud(attach).Result;
  202. //if (resPath != "")
  203. // attach.FilePath = resPath;
  204. }
  205. }
  206. }
  207. public bool CopyFileToActualFolder(string FileName)
  208. {
  209. throw new NotImplementedException();
  210. }
  211. public bool DeleteFileFromTempFolder(string FileName)
  212. {
  213. throw new NotImplementedException();
  214. }
  215. public string GetTempAttachmentPath()
  216. {
  217. throw new NotImplementedException();
  218. }
  219. public string GetActualAttachmentPath()
  220. {
  221. throw new NotImplementedException();
  222. }
  223. public Task<Tuple<MemoryStream, string, string>> GetFileDownloadInfo(string fileUrl)
  224. {
  225. throw new NotImplementedException();
  226. }
  227. public Task<bool> CopyFileToActualFolder(List<AttachmentDto> attachments)
  228. {
  229. throw new NotImplementedException();
  230. }
  231. string[] ImageExtensions = new string[]
  232. {
  233. ".JPEG"
  234. , ".JPG"
  235. , ".PNG"
  236. };
  237. }
  238. }