AzureStorageBlobExtensions.cs 12 KB

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