AzureBlobDBRepository.cs 36 KB

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