AzureStorageBlobExtensions.cs 12 KB

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