AzureStorageBlobExtensions.cs 12 KB

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