BlobFileService.cs 9.0 KB

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