AzureStorageBlobExtensions.cs 11 KB

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