AzureStorageBlobExtensions.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. using System.Threading.Tasks;
  2. using Azure.Storage;
  3. using Azure.Storage.Blobs;
  4. using Azure.Storage.Blobs.Models;
  5. using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
  6. using TEAMModelOS.SDK.Module.AzureBlob.Container;
  7. using TEAMModelOS.SDK.Context.Constant;
  8. using TEAMModelOS.SDK.Helper.Security.ShaHash;
  9. using System;
  10. using System.IO;
  11. using Azure.Storage.Blobs.Specialized;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. namespace TEAMModelOS.SDK.DI
  15. {
  16. public static class AzureStorageBlobExtensions
  17. {
  18. /// <summary>
  19. /// 取得指定前置詞的 Blob 名稱的總大小(Bytes),例如指定目錄名稱為前置詞
  20. /// </summary>
  21. /// <param name="prefix">篩選開頭名稱,Null代表容器總大小</param>
  22. /// <returns>總大小(Bytes),如果為Null代表查無前置詞或者發生錯誤</returns>
  23. public static async Task<long?> GetBlobsSize(this BlobContainerClient client, string prefix = null)
  24. {
  25. long? size = 0;
  26. try
  27. {
  28. await foreach (var item in client.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  29. {
  30. size += item.Properties.ContentLength;
  31. };
  32. return size;
  33. }
  34. catch
  35. {
  36. return size;
  37. }
  38. }
  39. /// <summary>
  40. /// 批量刪除Blobs
  41. /// </summary>
  42. /// <param name="prefix">篩選開頭名稱,Null代表容器</param>
  43. public static async Task<bool> DelectBlobs(this BlobServiceClient client, string blobContainerName, string prefix = null)
  44. {
  45. if (string.IsNullOrWhiteSpace(prefix)) return false;
  46. try
  47. {
  48. BlobContainerClient bcc = client.GetBlobContainerClient(blobContainerName);
  49. BlobBatchClient bbc = client.GetBlobBatchClient();
  50. List<Uri> blobs = new List<Uri>();
  51. await foreach (var item in bcc.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix))
  52. {
  53. var urib = new UriBuilder(bcc.Uri);
  54. urib.Path += "/" + item.Name;
  55. blobs.Add(urib.Uri);
  56. };
  57. if (blobs.Count <= 256)
  58. {
  59. await bbc.DeleteBlobsAsync(blobs);
  60. return true;
  61. }
  62. else
  63. {
  64. int pages = (blobs.Count + 255) / 256; //256是批量操作最大值,pages = (total + max -1) / max;
  65. for (int i = 0; i < pages; i++)
  66. {
  67. List<Uri> lists = blobs.Skip((i) * 256).Take(256).ToList();
  68. await bbc.DeleteBlobsAsync(lists);
  69. }
  70. return true;
  71. }
  72. }
  73. catch
  74. {
  75. return false;
  76. }
  77. }
  78. /// <summary>
  79. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  80. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  81. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  82. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  83. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  84. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  85. /// 答案及学习活动上传的文件,学生基本信息关联
  86. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  87. /// </summary>
  88. /// <param name="name">容器名称</param>
  89. /// <param name="json">文件内容的流</param>
  90. /// <param name="folder">业务文件夹</param>
  91. /// <param name="fileName">文件名</param>
  92. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  93. /// <returns></returns>
  94. public static async Task<string> UploadFileByContainer(this AzureStorageFactory azureStorage, string name, string json, string root , string blobpath, bool contentTypeDefault = true)
  95. {
  96. // string groupName =folder;
  97. BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  98. var blockBlob = blobContainer.GetBlobClient($"{root}/{blobpath}");
  99. string content_type = "application/octet-stream";
  100. if (!contentTypeDefault)
  101. {
  102. string fileext = blobpath.Substring(blobpath.LastIndexOf(".") > 0 ? blobpath.LastIndexOf(".") : 0);
  103. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  104. if (!string.IsNullOrEmpty(contenttype))
  105. {
  106. content_type = contenttype;
  107. }
  108. else
  109. {
  110. //blockBlob.Properties.ContentType = content_type;
  111. }
  112. }
  113. else
  114. {
  115. //blockBlob.Properties.ContentType = content_type;
  116. }
  117. byte[] bytes = System.Text.Encoding.Default.GetBytes(json);
  118. Stream streamBlob = new MemoryStream(bytes);
  119. await blockBlob.UploadAsync(streamBlob, true);
  120. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  121. return blockBlob.Uri.ToString();
  122. }
  123. /// <summary>
  124. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  125. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  126. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  127. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  128. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  129. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  130. /// 答案及学习活动上传的文件,学生基本信息关联
  131. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  132. /// </summary>
  133. /// <param name="name">容器名称</param>
  134. /// <param name="stream">文件内容的流</param>
  135. /// <param name="folder">业务文件夹</param>
  136. /// <param name="fileName">文件名</param>
  137. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  138. /// <returns></returns>
  139. public static async Task<AzureBlobModel> UploadFileByContainer(this AzureStorageFactory azureStorage, string name, Stream stream, string folder, string fileName, bool contentTypeDefault = true)
  140. {
  141. // string groupName =folder;
  142. BlobContainerClient blobContainer = azureStorage.GetBlobContainerClient(name.ToLower().Replace("#", "")); //blobClient.GetContainerReference(groupName);
  143. Uri url = blobContainer.Uri;
  144. var blockBlob = blobContainer.GetBlobClient(folder + "/" + fileName);
  145. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  146. string content_type = "application/octet-stream";
  147. if (!contentTypeDefault)
  148. {
  149. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  150. if (!string.IsNullOrEmpty(contenttype))
  151. {
  152. content_type = contenttype;
  153. }
  154. else
  155. {
  156. //blockBlob.Properties.ContentType = content_type;
  157. }
  158. }
  159. else
  160. {
  161. //blockBlob.Properties.ContentType = content_type;
  162. }
  163. await blockBlob.UploadAsync(stream, true);
  164. blockBlob.SetHttpHeaders(new BlobHttpHeaders { ContentType = content_type });
  165. AzureBlobModel model = new AzureBlobModel(fileName, name, folder, fileName, folder, content_type, stream.Length)
  166. {
  167. Sha1Code = ShaHashHelper.GetSHA1(stream),
  168. BlobUrl = blockBlob.Uri.ToString()
  169. };
  170. return model;
  171. }
  172. }
  173. }