AzureBlobDBRepository.cs 42 KB

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