AzureBlobDBRepository.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. //using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
  2. //using TEAMModelOS.SDK.Module.AzureBlob.Container;
  3. //using TEAMModelOS.SDK.Module.AzureBlob.Interfaces;
  4. //using System;
  5. //using System.Collections.Generic;
  6. //using System.IO;
  7. //using System.Net.Http.Headers;
  8. //using System.Threading.Tasks;
  9. //using TEAMModelOS.SDK.Helper.Security.AESCrypt;
  10. //using TEAMModelOS.SDK.Context.Exception;
  11. //using Microsoft.AspNetCore.Http;
  12. //using TEAMModelOS.SDK.Extension.SnowFlake;
  13. //using TEAMModelOS.SDK.Context.Constant;
  14. //using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  15. //using TEAMModelOS.SDK.Helper.Security.ShaHash;
  16. //using Microsoft.Extensions.Configuration;
  17. //using TEAMModelOS.SDK.Context.Configuration;
  18. //using Microsoft.AspNetCore.Hosting;
  19. //using Microsoft.Azure.Cosmos.Linq;
  20. //using System.Reflection.Metadata;
  21. //using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  22. //using Jaeger.Util;
  23. //namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
  24. //{
  25. // public class AzureBlobDBRepository : IAzureBlobDBRepository
  26. // {
  27. // public CloudBlobClient blobClient;
  28. // public CloudBlobContainer blobContainer;
  29. // public AzureBlobOptions _options;
  30. // public IConfiguration Configuration { get; }
  31. // public AzureBlobDBRepository(IConfiguration configuration, IWebHostEnvironment env, AzureBlobOptions options, AzureBlobOptions azureBlobOptions)
  32. // {
  33. // Configuration = configuration;
  34. // // BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
  35. // _options = options;
  36. // if (!string.IsNullOrEmpty(options.ConnectionString))
  37. // {
  38. // blobClient = BlobClientSingleton.getInstance(options.ConnectionString).GetBlobClient();
  39. // }
  40. // else { throw new BizException("请设置正确的AzureBlob文件存储配置信息!"); }
  41. // }
  42. // public AzureBlobDBRepository()
  43. // {
  44. // }
  45. // private CloudBlobContainer InitializeBlob(string container)
  46. // {
  47. // //https://teammodelstorage.blob.core.chinacloudapi.cn/wechatfilescontainer
  48. // // Type t = typeof(T);
  49. // //若要将权限设置为仅针对 blob 的公共读取访问,请将 PublicAccess 属性设置为 BlobContainerPublicAccessType.Blob。
  50. // //要删除匿名用户的所有权限,请将该属性设置为 BlobContainerPublicAccessType.Off。
  51. // blobContainer = blobClient.GetContainerReference(_options .Container+"/"+ container);
  52. // // await blobContainer.CreateIfNotExistsAsync();
  53. // // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  54. // // permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
  55. // // await blobContainer.SetPermissionsAsync(permissions);
  56. // return blobContainer;
  57. // }
  58. // public async Task<List<AzureBlobModel>> UploadFiles(IFormFile[] file,string fileSpace= "common" , bool contentTypeDefault = false)
  59. // {
  60. // string groupName = fileSpace+"/" +DateTime.Now.ToString("yyyyMMdd");
  61. // string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  62. // // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  63. // blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  64. // //var serviceProperties = await blobClient.GetServicePropertiesAsync();
  65. // //var corsSettings = serviceProperties.Cors;
  66. // //var corsRule = corsSettings.CorsRules.FirstOrDefault(
  67. // // o => o.AllowedOrigins.Contains("http://localhost:3904"));//设置你自己的服务器地址
  68. // //if (corsRule == null)
  69. // //{
  70. // // //Add a new rule.
  71. // // corsRule = new CorsRule()
  72. // // {
  73. // // AllowedHeaders = new List<string> { "x-ms-*", "content-type", "accept" },
  74. // // AllowedMethods = CorsHttpMethods.Put| CorsHttpMethods.Head | CorsHttpMethods.Post | CorsHttpMethods.Merge | CorsHttpMethods.Get,//Since we'll only be calling Put Blob, let's just allow PUT verb
  75. // // AllowedOrigins = new List<string> { "http://localhost:3904" },//This is the URL of our application.
  76. // // ExposedHeaders = { },
  77. // // MaxAgeInSeconds = 1 * 60 * 60,//Let the browswer cache it for an hour
  78. // // };
  79. // // corsSettings.CorsRules.Add(corsRule);
  80. // // //Save the rule
  81. // // await blobClient.SetServicePropertiesAsync(serviceProperties);
  82. // //}
  83. // StorageUri url = blobContainer.StorageUri;
  84. // List<AzureBlobModel> list = new List<AzureBlobModel>();
  85. // foreach (FormFile f in file)
  86. // {
  87. // string[] names = f.FileName.Split(".");
  88. // string name = "";
  89. // for (int i = 0; i < names.Length-1; i++) {
  90. // name = name + names[i];
  91. // }
  92. // if (names.Length <= 1)
  93. // {
  94. // name = f.FileName + "_" + newFileName;
  95. // }
  96. // else {
  97. // name = name + "_" + newFileName + "." + names[names.Length - 1];
  98. // }
  99. // string fileext = f.FileName.Substring(f.FileName.LastIndexOf(".")>0? f.FileName.LastIndexOf("."):0);
  100. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse(f.ContentDisposition);
  101. // var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  102. // var blockBlob = blobContainer.GetBlockBlobReference(name);
  103. // if (!contentTypeDefault) {
  104. // ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  105. // if (!string.IsNullOrEmpty(content_type))
  106. // {
  107. // blockBlob.Properties.ContentType = content_type;
  108. // }
  109. // }
  110. // await blockBlob.UploadFromStreamAsync(f.OpenReadStream());
  111. // string sha1= ShaHashHelper.GetSHA1(f.OpenReadStream());
  112. // AzureBlobModel model = new AzureBlobModel(f, _options.Container, groupName, name)
  113. // {
  114. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name,
  115. // Sha1Code = sha1
  116. // };
  117. // list.Add(model);
  118. // }
  119. // return list;
  120. // }
  121. // public async Task<AzureBlobModel> UploadPath(string path, string fileSpace = "common" , bool contentTypeDefault = false) {
  122. // string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  123. // string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  124. // blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  125. // StorageUri url = blobContainer.StorageUri;
  126. // FileInfo file = new FileInfo(path);
  127. // string[] names = file.Name.Split(".");
  128. // string name = "";
  129. // for (int i = 0; i < names.Length - 1; i++)
  130. // {
  131. // name = name + names[i];
  132. // }
  133. // if (names.Length <= 1)
  134. // {
  135. // name = file.Name + "_" + newFileName;
  136. // }
  137. // else
  138. // {
  139. // name = name + "_" + newFileName + "." + names[names.Length - 1];
  140. // }
  141. // string fileext = file.Name.Substring(file.Name.LastIndexOf(".") > 0 ? file.Name.LastIndexOf(".") : 0);
  142. // // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  143. // var blockBlob = blobContainer.GetBlockBlobReference(name);
  144. // string content_type = "application/octet-stream";
  145. // if (!contentTypeDefault)
  146. // {
  147. // ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  148. // if (!string.IsNullOrEmpty(contenttype))
  149. // {
  150. // blockBlob.Properties.ContentType = contenttype;
  151. // content_type = contenttype;
  152. // }
  153. // else
  154. // {
  155. // blockBlob.Properties.ContentType = content_type;
  156. // }
  157. // }
  158. // else
  159. // {
  160. // blockBlob.Properties.ContentType = content_type;
  161. // }
  162. // await blockBlob.UploadFromFileAsync(path);
  163. // //var provider = new FileExtensionContentTypeProvider();
  164. // //var memi = provider.Mappings[fileext];
  165. // AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name , content_type)
  166. // {
  167. // Sha1Code=ShaHashHelper.GetSHA1(file.Create()),
  168. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  169. // };
  170. // return model;
  171. // }
  172. // public async Task<AzureBlobModel> UploadText(string fileName, string text, string fileSpace = "common", bool contentTypeDefault = true)
  173. // {
  174. // string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  175. // string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  176. // blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  177. // StorageUri url = blobContainer.StorageUri;
  178. // //FileInfo file = new FileInfo(path);
  179. // string[] names = fileName.Split(".");
  180. // string name = "";
  181. // for (int i = 0; i < names.Length - 1; i++)
  182. // {
  183. // name = name + names[i];
  184. // }
  185. // if (names.Length <= 1)
  186. // {
  187. // name = fileName + "_" + newFileName;
  188. // }
  189. // else
  190. // {
  191. // name = name + "_" + newFileName + "." + names[names.Length - 1];
  192. // }
  193. // var blockBlob = blobContainer.GetBlockBlobReference(name);
  194. // // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  195. // string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  196. // string content_type = "application/octet-stream";
  197. // if (!contentTypeDefault)
  198. // {
  199. // ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  200. // if (!string.IsNullOrEmpty(contenttype))
  201. // {
  202. // blockBlob.Properties.ContentType = contenttype;
  203. // content_type = contenttype;
  204. // }
  205. // else
  206. // {
  207. // blockBlob.Properties.ContentType = content_type;
  208. // }
  209. // }
  210. // else
  211. // {
  212. // blockBlob.Properties.ContentType = content_type;
  213. // }
  214. // await blockBlob.UploadTextAsync(text);
  215. // byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
  216. // //var provider = new FileExtensionContentTypeProvider();
  217. // //var memi = provider.Mappings[fileext];
  218. // AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type, bytes.Length)
  219. // {
  220. // Sha1Code = ShaHashHelper.GetSHA1(bytes),
  221. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  222. // };
  223. // return model;
  224. // }
  225. // public async Task<AzureBlobModel> UploadObject(string fileName,object obj, string fileSpace = "common", bool contentTypeDefault =true)
  226. // {
  227. // string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  228. // string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  229. // blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  230. // StorageUri url = blobContainer.StorageUri;
  231. // //FileInfo file = new FileInfo(path);
  232. // string[] names = fileName.Split(".");
  233. // string name = "";
  234. // for (int i = 0; i < names.Length - 1; i++)
  235. // {
  236. // name = name + names[i];
  237. // }
  238. // if (names.Length <= 1)
  239. // {
  240. // name = fileName + "_" + newFileName;
  241. // }
  242. // else
  243. // {
  244. // name = name + "_" + newFileName + "." + names[names.Length - 1];
  245. // }
  246. // var blockBlob = blobContainer.GetBlockBlobReference(name);
  247. // // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  248. // string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  249. // string content_type = "application/octet-stream";
  250. // if (!contentTypeDefault)
  251. // {
  252. // ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  253. // if (!string.IsNullOrEmpty(contenttype))
  254. // {
  255. // blockBlob.Properties.ContentType = contenttype;
  256. // content_type = contenttype;
  257. // }
  258. // else
  259. // {
  260. // blockBlob.Properties.ContentType = content_type;
  261. // }
  262. // }
  263. // else {
  264. // blockBlob.Properties.ContentType = content_type;
  265. // }
  266. // string objStr = obj.ToJsonAbs();
  267. // await blockBlob.UploadTextAsync(objStr);
  268. // //var provider = new FileExtensionContentTypeProvider();
  269. // //var memi = provider.Mappings[fileext];
  270. // byte[] bytes = System.Text.Encoding.Default.GetBytes(objStr);
  271. // AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type , bytes.Length)
  272. // {
  273. // Sha1Code = ShaHashHelper.GetSHA1(bytes),
  274. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  275. // };
  276. // return model;
  277. // }
  278. // public async Task<AzureBlobModel> UploadFile(IFormFile file, string fileSpace = "wordfiles", bool contentTypeDefault = true)
  279. // {
  280. // long bizno= IdWorker.getInstance().NextId();
  281. // string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd")+"/"+ bizno;
  282. // string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  283. // // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  284. // blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  285. // StorageUri url = blobContainer.StorageUri;
  286. // string[] names = file.FileName.Split(".");
  287. // string name = "";
  288. // for (int i = 0; i < names.Length - 1; i++)
  289. // {
  290. // name = name + names[i];
  291. // }
  292. // if (names.Length <= 1)
  293. // {
  294. // name = name + "_" + newFileName;
  295. // }
  296. // else
  297. // {
  298. // name = name + "_" + newFileName + "." + names[names.Length - 1];
  299. // }
  300. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  301. // var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  302. // var blockBlob = blobContainer.GetBlockBlobReference(name);
  303. // string fileext = filename.Substring(filename.LastIndexOf(".") > 0 ? filename.LastIndexOf(".") : 0);
  304. // if (!contentTypeDefault)
  305. // {
  306. // ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  307. // if (!string.IsNullOrEmpty(content_type))
  308. // {
  309. // blockBlob.Properties.ContentType = content_type;
  310. // }
  311. // }
  312. // await blockBlob.UploadFromStreamAsync(file.OpenReadStream());
  313. // string sha1 = ShaHashHelper.GetSHA1(file.OpenReadStream());
  314. // AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name)
  315. // {
  316. // Sha1Code=sha1,
  317. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  318. // };
  319. // return model;
  320. // }
  321. // public AzureBlobModel UploadFileByFolderNAsyn(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  322. // {
  323. // string groupName = fileSpace + "/" + folder;
  324. // blobContainer = InitializeBlob(groupName);
  325. // StorageUri url = blobContainer.StorageUri;
  326. // string[] names = fileName.Split(".");
  327. // var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  328. // string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  329. // if (!contentTypeDefault)
  330. // {
  331. // ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  332. // if (!string.IsNullOrEmpty(content_type))
  333. // {
  334. // blockBlob.Properties.ContentType = content_type;
  335. // }
  336. // else
  337. // {
  338. // blockBlob.Properties.ContentType = "application/octet-stream";
  339. // }
  340. // }
  341. // blockBlob.UploadFromStreamAsync(fileSteam).GetAwaiter().GetResult() ;
  342. // AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
  343. // {
  344. // Sha1Code = ShaHashHelper.GetSHA1(fileSteam),
  345. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  346. // };
  347. // return model;
  348. // }
  349. // public async Task<AzureBlobModel> UploadFileByFolder(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  350. // {
  351. // string groupName = fileSpace + "/" + folder;
  352. // // string newFileName = sha1Code;
  353. // // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  354. // blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  355. // StorageUri url = blobContainer.StorageUri;
  356. // string[] names = fileName.Split(".");
  357. // // string name ;
  358. // //for (int i = 0; i < names.Length - 1; i++)
  359. // //{
  360. // // name = name + names[i];
  361. // //}
  362. // //if (names.Length <= 1)
  363. // //{
  364. // // name = newFileName;
  365. // //}
  366. // //else
  367. // //{
  368. // // name = newFileName + "." + names[names.Length - 1];
  369. // //}
  370. // //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  371. // //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  372. // var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  373. // string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  374. // if (!contentTypeDefault)
  375. // {
  376. // ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  377. // if (!string.IsNullOrEmpty(content_type))
  378. // {
  379. // blockBlob.Properties.ContentType = content_type;
  380. // }
  381. // else {
  382. // blockBlob.Properties.ContentType = "application/octet-stream";
  383. // }
  384. // }
  385. // await blockBlob.UploadFromStreamAsync(fileSteam);
  386. // string sha1 = ShaHashHelper.GetSHA1(fileSteam);
  387. // AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
  388. // {
  389. // Sha1Code = sha1,
  390. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  391. // };
  392. // return model;
  393. // }
  394. // public async Task<AzureBlobModel> UploadTextByFolder(string text, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  395. // {
  396. // string groupName = fileSpace + "/" + folder;
  397. // blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  398. // StorageUri url = blobContainer.StorageUri;
  399. // var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  400. // string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  401. // string content_type = "application/octet-stream";
  402. // if (!contentTypeDefault)
  403. // {
  404. // ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  405. // if (!string.IsNullOrEmpty(contenttype))
  406. // {
  407. // blockBlob.Properties.ContentType = contenttype;
  408. // content_type = contenttype;
  409. // }
  410. // else
  411. // {
  412. // blockBlob.Properties.ContentType = content_type;
  413. // }
  414. // }
  415. // else
  416. // {
  417. // blockBlob.Properties.ContentType = content_type;
  418. // }
  419. // await blockBlob.UploadTextAsync(text);
  420. // byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
  421. // AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, bytes.Length)
  422. // {
  423. // Sha1Code = ShaHashHelper.GetSHA1(bytes),
  424. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  425. // };
  426. // return model;
  427. // }
  428. // /// <summary>
  429. // /// 在容器上创建共享访问策略。
  430. // /// </summary>
  431. // /// <param name="container">A reference to the container.</param>
  432. // /// <param name="policyName">The name of the stored access policy.</param>
  433. // public async Task<bool> CreateSharedAccessPolicyAsync(string policyName,
  434. // string containerName = null)
  435. // {
  436. // blobContainer = await CreateContainer(_options.Container);
  437. // //Create a new shared access policy and define its constraints.
  438. // SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
  439. // {
  440. // SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
  441. // Permissions = SharedAccessBlobPermissions.Delete
  442. // };
  443. // //Get the container's existing permissions.
  444. // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  445. // if (permissions.SharedAccessPolicies.Count < 5)
  446. // {
  447. // //Add the new policy to the container's permissions, and set the container's permissions.
  448. // permissions.SharedAccessPolicies.TryAdd(policyName, sharedPolicy);
  449. // await blobContainer.SetPermissionsAsync(permissions);
  450. // return true;
  451. // }
  452. // else return false;
  453. // }
  454. // /// <summary>
  455. // /// 删除容器上共享访问策略。
  456. // /// </summary>
  457. // /// <param name="container">A reference to the container.</param>
  458. // /// <param name="policyName">The name of the stored access policy.</param>
  459. // public async Task DeleteSharedAccessPolicyAsync(string policyName,
  460. // string containerName = null)
  461. // {
  462. // blobContainer = await CreateContainer(_options.Container);
  463. // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  464. // permissions.SharedAccessPolicies.Remove(policyName);
  465. // await blobContainer.SetPermissionsAsync(permissions);
  466. // }
  467. // /// <summary>
  468. // ///为 blob 容器创建服务 SAS
  469. // /// 若要为容器创建服务 SAS,请调用 CloudBlobContainer.GetSharedAccessSignature 方法。
  470. // ///下面的代码示例在容器上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在容器上创建一个临时 SAS。
  471. // /// </summary>
  472. // /// <param name="container"></param>
  473. // /// <param name="storedPolicyName"></param>
  474. // /// <returns></returns>
  475. // public async Task<(string, string, string)> GetContainerSasUri(string containerName = null, string storedPolicyName = null)
  476. // {
  477. // string sasContainerToken;
  478. // blobContainer = await CreateContainer(_options.Container);
  479. // // If no stored policy is specified, create a new access policy and define its constraints.
  480. // if (storedPolicyName == null)
  481. // {
  482. // // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  483. // // to construct a shared access policy that is saved to the container's shared access policies.
  484. // SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
  485. // {
  486. // // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  487. // // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  488. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  489. // SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  490. // Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create| SharedAccessBlobPermissions.Read
  491. // };
  492. // // Generate the shared access signature on the container, setting the constraints directly on the signature.
  493. // sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  494. // }
  495. // else
  496. // {
  497. // // Generate the shared access signature on the container. In this case, all of the constraints for the
  498. // // shared access signature are specified on the stored access policy, which is provided by name.
  499. // // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
  500. // sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
  501. // }
  502. // // Return the URI string for the container, including the SAS token.
  503. // return (blobContainer.Uri.Scheme+ "://"+ blobContainer.Uri.Host.ToString() , blobContainer.Name, sasContainerToken);
  504. // }
  505. // public async Task<(string, string)> GetContainerSasUriRead(string containerName, string storedPolicyName = null)
  506. // {
  507. // string sasContainerToken;
  508. // blobContainer = await CreateContainer(containerName);
  509. // // If no stored policy is specified, create a new access policy and define its constraints.
  510. // if (storedPolicyName == null)
  511. // {
  512. // // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  513. // // to construct a shared access policy that is saved to the container's shared access policies.
  514. // SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
  515. // {
  516. // // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  517. // // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  518. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  519. // SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
  520. // Permissions = SharedAccessBlobPermissions.Read
  521. // };
  522. // // Generate the shared access signature on the container, setting the constraints directly on the signature.
  523. // sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  524. // }
  525. // else
  526. // {
  527. // // Generate the shared access signature on the container. In this case, all of the constraints for the
  528. // // shared access signature are specified on the stored access policy, which is provided by name.
  529. // // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
  530. // sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
  531. // }
  532. // // Return the URI string for the container, including the SAS token.
  533. // return (blobContainer.Uri.ToString(), sasContainerToken);
  534. // }
  535. // /// <summary>
  536. // /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  537. // /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  538. // /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  539. // /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  540. // /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  541. // /// "teacher": [ "res", "item", "htex", "task", "info" ],
  542. // /// 答案及学习活动上传的文件,学生基本信息关联
  543. // ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  544. // /// </summary>
  545. // /// <param name="name">容器名称</param>
  546. // /// <param name="text">文件内容的流</param>
  547. // /// <param name="folder">业务文件夹</param>
  548. // /// <param name="fileName">文件名</param>
  549. // /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  550. // /// <returns></returns>
  551. // public async Task<AzureBlobModel> UploadFileByContainer(string name ,string text, string folder, string fileName, bool contentTypeDefault = true)
  552. // {
  553. // // string groupName =folder;
  554. // blobContainer = await CreateContainer(name.ToLower().Replace("#","")); //blobClient.GetContainerReference(groupName);
  555. // StorageUri url = blobContainer.StorageUri;
  556. // var blockBlob = blobContainer.GetBlockBlobReference(folder+"/"+fileName);
  557. // string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  558. // string content_type = "application/octet-stream";
  559. // if (!contentTypeDefault)
  560. // {
  561. // ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  562. // if (!string.IsNullOrEmpty(contenttype))
  563. // {
  564. // blockBlob.Properties.ContentType = contenttype;
  565. // content_type = contenttype;
  566. // }
  567. // else
  568. // {
  569. // blockBlob.Properties.ContentType = content_type;
  570. // }
  571. // }
  572. // else
  573. // {
  574. // blockBlob.Properties.ContentType = content_type;
  575. // }
  576. // await blockBlob.UploadTextAsync(text);
  577. // byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
  578. // AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, folder, fileName, folder, blockBlob.Properties.ContentType, bytes.Length)
  579. // {
  580. // Sha1Code = ShaHashHelper.GetSHA1(bytes),
  581. // BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  582. // };
  583. // return model;
  584. // }
  585. // public async Task<BlobAuth> GetContainerSasUri(BlobSas blobSas, bool isRead)
  586. // {
  587. // CloudBlobContainer blobContainer;
  588. // if (blobSas.role == "system")
  589. // {
  590. // blobContainer = await CreateContainer(_options.Container);
  591. // }
  592. // else
  593. // {
  594. // blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#", ""));
  595. // }
  596. // // If no stored policy is specified, create a new access policy and define its constraints.
  597. // // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  598. // // to construct a shared access policy that is saved to the container's shared access policies.
  599. // DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
  600. // long time = dateTime.ToUnixTimeMilliseconds();
  601. // SharedAccessBlobPolicy adHocPolicy = null;
  602. // if (isRead)
  603. // {
  604. // adHocPolicy = new SharedAccessBlobPolicy()
  605. // {
  606. // // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  607. // // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  608. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  609. // SharedAccessExpiryTime = dateTime,
  610. // Permissions = SharedAccessBlobPermissions.Read
  611. // };
  612. // }
  613. // else {
  614. // adHocPolicy = new SharedAccessBlobPolicy()
  615. // {
  616. // // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  617. // // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  618. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  619. // SharedAccessExpiryTime = dateTime,
  620. // Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read| SharedAccessBlobPermissions.List
  621. // };
  622. // }
  623. // // Generate the shared access signature on the container, setting the constraints directly on the signature.
  624. // string sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  625. // return new BlobAuth { url = blobContainer.Uri.AbsoluteUri.Replace(blobContainer.Uri.AbsolutePath,""), sas = sasContainerToken, timeout = time,name = blobContainer.Name };
  626. // }
  627. // public async Task<Dictionary<string,object>> GetBlobSasUri(BlobSas blobSas,bool isRead) {
  628. // string sasBlobToken;
  629. // CloudBlobContainer blobContainer;
  630. // if (blobSas.role == "system")
  631. // {
  632. // blobContainer = await CreateContainer(_options.Container);
  633. // }
  634. // else {
  635. // blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#",""));
  636. // }
  637. // // Create a new access policy and define its constraints.
  638. // // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  639. // // to construct a shared access policy that is saved to the container's shared access policies.
  640. // DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
  641. // SharedAccessBlobPolicy adHocSAS = null;
  642. // if (isRead)
  643. // {
  644. // adHocSAS = new SharedAccessBlobPolicy()
  645. // {
  646. // // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  647. // // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  648. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
  649. // SharedAccessExpiryTime = dateTime,
  650. // Permissions = SharedAccessBlobPermissions.Read
  651. // };
  652. // }
  653. // else
  654. // {
  655. // adHocSAS = new SharedAccessBlobPolicy()
  656. // {
  657. // // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  658. // // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  659. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
  660. // SharedAccessExpiryTime = dateTime,
  661. // Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
  662. // };
  663. // }
  664. // Dictionary<string, object> dict = new Dictionary<string, object>();
  665. // long time = dateTime.ToUnixTimeMilliseconds();
  666. // List<string> folders = BaseConfigModel.Configuration.GetSection("Azure:Blob:" + blobSas.role).Get<List<string>>();
  667. // if (folders.IsNotEmpty())
  668. // {
  669. // foreach (string floder in folders) {
  670. // string cates = floder;
  671. // if (blobSas.role == "student") {
  672. // if (string.IsNullOrEmpty(blobSas.code)) {
  673. // throw new BizException("请设置学生编码!", ResponseCode.PARAMS_ERROR);
  674. // }
  675. // cates = floder.Replace("{studentId}", blobSas.code);
  676. // }
  677. // // Get a reference to a blob within the container.
  678. // // Note that the blob may not exist yet, but a SAS can still be created for it.
  679. // CloudBlockBlob blob = blobContainer.GetBlockBlobReference(cates);
  680. // // Generate the shared access signature on the blob, setting the constraints directly on the signature.
  681. // sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  682. // dict.Add(cates, new { url=blob.Uri,sas=sasBlobToken , timeout = time });
  683. // }
  684. // }
  685. // return dict;
  686. // }
  687. // /// <summary>
  688. // /// 若要为 blob 创建服务 SAS,请调用 CloudBlob.GetSharedAccessSignature 方法。
  689. // ///下面的代码示例在 blob 上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在 Blob 上创建一个临时 SAS。
  690. // /// </summary>
  691. // /// <param name="container"></param>
  692. // /// <param name="blobName"></param>
  693. // /// <param name="policyName"></param>
  694. // /// <returns></returns>
  695. // public async Task<string> GetBlobSasUri(string blobName, string containerName=null, string policyName = null)
  696. // {
  697. // string sasBlobToken;
  698. // blobContainer =await CreateContainer(_options.Container);
  699. // // Get a reference to a blob within the container.
  700. // // Note that the blob may not exist yet, but a SAS can still be created for it.
  701. // CloudBlockBlob blob = blobContainer.GetBlockBlobReference( blobName );
  702. // if (policyName == null)
  703. // {
  704. // // Create a new access policy and define its constraints.
  705. // // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  706. // // to construct a shared access policy that is saved to the container's shared access policies.
  707. // SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  708. // {
  709. // // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
  710. // // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  711. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  712. // SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  713. // Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
  714. // };
  715. // // Generate the shared access signature on the blob, setting the constraints directly on the signature.
  716. // sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  717. // }
  718. // else
  719. // {
  720. // // Generate the shared access signature on the blob. In this case, all of the constraints for the
  721. // // shared access signature are specified on the container's stored access policy.
  722. // sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
  723. // }
  724. // // Return the URI string for the container, including the SAS token.
  725. // return blob.Uri + sasBlobToken;
  726. // }
  727. // public async Task<List<BlobFileDto>> GetBlobDirectory(string containerName, string blobName)
  728. // {
  729. // blobContainer = await CreateContainer(containerName);
  730. // CloudBlobDirectory cloudBlobDirectory = blobContainer.GetDirectoryReference(blobName);
  731. // List<BlobFileDto> blobProperties = new List<BlobFileDto>();
  732. // blobProperties = GetBlobProperties(blobProperties, cloudBlobDirectory);
  733. // return blobProperties;
  734. // }
  735. // public List<BlobFileDto> GetBlobProperties(List<BlobFileDto> blobProperties, CloudBlobDirectory blobDirectory)
  736. // {
  737. // IEnumerable<IListBlobItem> listBlobItems1 = blobDirectory.ListBlobsSegmentedAsync(new BlobContinuationToken()).GetAwaiter().GetResult().Results;
  738. // foreach (IListBlobItem listBlobItem in listBlobItems1)
  739. // {
  740. // if (listBlobItem.GetType() == typeof(CloudBlobDirectory))
  741. // {
  742. // CloudBlobDirectory cloudBlobDirectory = (CloudBlobDirectory)listBlobItem;
  743. // blobProperties = GetBlobProperties(blobProperties, cloudBlobDirectory);
  744. // }
  745. // else
  746. // {
  747. // CloudBlob blobaa = (CloudBlob)listBlobItem;
  748. // blobaa.FetchAttributesAsync();
  749. // BlobFileDto blobFileDto = new BlobFileDto
  750. // {
  751. // name = blobaa.Name,
  752. // length = blobaa.Properties.Length,
  753. // contentType = blobaa.Properties.ContentType,
  754. // created = blobaa.Properties.Created != null ? blobaa.Properties.Created.Value.ToUnixTimeMilliseconds() : 0,//blobaa.Properties.Created.IsNull() ? 0 :
  755. // lastModified = blobaa.Properties.LastModified != null ? blobaa.Properties.LastModified.Value.ToUnixTimeMilliseconds() : 0,//blobaa.Properties.LastModified.IsNull()? 0:
  756. // url = blobaa.Uri.AbsoluteUri,
  757. // BlobType = blobaa.BlobType.ToString()
  758. // };
  759. // blobProperties.Add(blobFileDto);
  760. // }
  761. // }
  762. // return blobProperties;
  763. // }
  764. // public async Task<string> GetBlobSasUriRead(string containerName, string blobName, string policyName = null)
  765. // {
  766. // string sasBlobToken;
  767. // blobContainer = await CreateContainer(containerName);
  768. // CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
  769. // if (policyName == null)
  770. // {
  771. // SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  772. // {
  773. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  774. // SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  775. // Permissions = SharedAccessBlobPermissions.Read
  776. // };
  777. // sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  778. // }
  779. // else
  780. // {
  781. // sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
  782. // }
  783. // return blob.Uri + sasBlobToken;
  784. // }
  785. // public async Task<BlobAuth> GetBlobSasUriRead(string containerName, string blobName)
  786. // {
  787. // string sasBlobToken;
  788. // blobContainer = await GetContainer(containerName);
  789. // CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
  790. // DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
  791. // long time = dateTime.ToUnixTimeMilliseconds();
  792. // SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  793. // {
  794. // SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  795. // SharedAccessExpiryTime = dateTime,
  796. // Permissions = SharedAccessBlobPermissions.Read
  797. // };
  798. // sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  799. // return new BlobAuth { url = blob.Uri.ToString(), sas = sasBlobToken, timeout = time };
  800. // }
  801. // private async Task<CloudBlobContainer> CreateContainer(string containerName)
  802. // {
  803. // CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_options.ConnectionString);
  804. // CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  805. // CloudBlobContainer container = blobClient.GetContainerReference(containerName);
  806. // await container.CreateIfNotExistsAsync();
  807. // return container;
  808. // }
  809. // private async Task<CloudBlobContainer> GetContainer(string containerName)
  810. // {
  811. // CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_options.ConnectionString);
  812. // CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  813. // CloudBlobContainer container = blobClient.GetContainerReference(containerName);
  814. // bool a = await container.ExistsAsync();
  815. // if (!a) {
  816. // throw new BizException("容器不存在!",ResponseCode.PARAMS_ERROR);
  817. // }
  818. // // await container.CreateIfNotExistsAsync();
  819. // return container;
  820. // }
  821. // public async Task Deleteblob(string azureBlobSAS)
  822. // {
  823. // (string, string) a = BlobUrlString(azureBlobSAS);
  824. // string ContainerName = a.Item1;
  825. // string BlobName = a.Item2;
  826. // string PolicyName = "DeletePolicy";
  827. // try
  828. // {
  829. // bool flg = await CreateSharedAccessPolicyAsync(PolicyName);
  830. // if (flg)
  831. // {
  832. // string SAS = await GetBlobSasUri(BlobName, null, PolicyName);
  833. // CloudBlockBlob blob = new CloudBlockBlob(new Uri(SAS));
  834. // await blob.DeleteAsync();
  835. // }
  836. // // await DeleteSharedAccessPolicyAsync(PolicyName);
  837. // }
  838. // catch (Exception e) {
  839. // throw new BizException(e.StackTrace);
  840. // }
  841. // finally {
  842. // await DeleteSharedAccessPolicyAsync(PolicyName);
  843. // }
  844. // }
  845. // private static (string, string) BlobUrlString(string sasUrl)
  846. // {
  847. // sasUrl = sasUrl.Substring(8);
  848. // string[] sasUrls = sasUrl.Split("/");
  849. // string ContainerName;
  850. // ContainerName = sasUrls[1].Clone().ToString();
  851. // string item = sasUrls[0] + "/" + sasUrls[1] + "/";
  852. // string blob = sasUrl.Replace(item, "");
  853. // return (ContainerName, blob);
  854. // }
  855. // }
  856. //}