AzureStorageBlobExtensions.cs 10 KB

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