AzureBlobDBRepository.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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. blobContainer = InitializeBlob(groupName);
  327. StorageUri url = blobContainer.StorageUri;
  328. string[] names = fileName.Split(".");
  329. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  330. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  331. if (!contentTypeDefault)
  332. {
  333. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  334. if (!string.IsNullOrEmpty(content_type))
  335. {
  336. blockBlob.Properties.ContentType = content_type;
  337. }
  338. else
  339. {
  340. blockBlob.Properties.ContentType = "application/octet-stream";
  341. }
  342. }
  343. blockBlob.UploadFromStreamAsync(fileSteam).GetAwaiter().GetResult() ;
  344. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
  345. {
  346. Sha1Code = ShaHashHelper.GetSHA1(fileSteam),
  347. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  348. };
  349. return model;
  350. }
  351. public async Task<AzureBlobModel> UploadFileByFolder(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  352. {
  353. string groupName = fileSpace + "/" + folder;
  354. // string newFileName = sha1Code;
  355. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  356. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  357. StorageUri url = blobContainer.StorageUri;
  358. string[] names = fileName.Split(".");
  359. // string name ;
  360. //for (int i = 0; i < names.Length - 1; i++)
  361. //{
  362. // name = name + names[i];
  363. //}
  364. //if (names.Length <= 1)
  365. //{
  366. // name = newFileName;
  367. //}
  368. //else
  369. //{
  370. // name = newFileName + "." + names[names.Length - 1];
  371. //}
  372. //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  373. //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  374. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  375. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  376. if (!contentTypeDefault)
  377. {
  378. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  379. if (!string.IsNullOrEmpty(content_type))
  380. {
  381. blockBlob.Properties.ContentType = content_type;
  382. }
  383. else {
  384. blockBlob.Properties.ContentType = "application/octet-stream";
  385. }
  386. }
  387. await blockBlob.UploadFromStreamAsync(fileSteam);
  388. string sha1 = ShaHashHelper.GetSHA1(fileSteam);
  389. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
  390. {
  391. Sha1Code = sha1,
  392. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  393. };
  394. return model;
  395. }
  396. public async Task<AzureBlobModel> UploadTextByFolder(string text, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  397. {
  398. string groupName = fileSpace + "/" + folder;
  399. blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
  400. StorageUri url = blobContainer.StorageUri;
  401. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  402. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  403. string content_type = "application/octet-stream";
  404. if (!contentTypeDefault)
  405. {
  406. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  407. if (!string.IsNullOrEmpty(contenttype))
  408. {
  409. blockBlob.Properties.ContentType = contenttype;
  410. content_type = contenttype;
  411. }
  412. else
  413. {
  414. blockBlob.Properties.ContentType = content_type;
  415. }
  416. }
  417. else
  418. {
  419. blockBlob.Properties.ContentType = content_type;
  420. }
  421. await blockBlob.UploadTextAsync(text);
  422. byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
  423. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, bytes.Length)
  424. {
  425. Sha1Code = ShaHashHelper.GetSHA1(bytes),
  426. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  427. };
  428. return model;
  429. }
  430. /// <summary>
  431. /// 在容器上创建共享访问策略。
  432. /// </summary>
  433. /// <param name="container">A reference to the container.</param>
  434. /// <param name="policyName">The name of the stored access policy.</param>
  435. public async Task<bool> CreateSharedAccessPolicyAsync(string policyName,
  436. string containerName = null)
  437. {
  438. blobContainer = await CreateContainer(_options.Container);
  439. //Create a new shared access policy and define its constraints.
  440. SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
  441. {
  442. SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
  443. Permissions = SharedAccessBlobPermissions.Delete
  444. };
  445. //Get the container's existing permissions.
  446. BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  447. if (permissions.SharedAccessPolicies.Count < 5)
  448. {
  449. //Add the new policy to the container's permissions, and set the container's permissions.
  450. permissions.SharedAccessPolicies.TryAdd(policyName, sharedPolicy);
  451. await blobContainer.SetPermissionsAsync(permissions);
  452. return true;
  453. }
  454. else return false;
  455. }
  456. /// <summary>
  457. /// 删除容器上共享访问策略。
  458. /// </summary>
  459. /// <param name="container">A reference to the container.</param>
  460. /// <param name="policyName">The name of the stored access policy.</param>
  461. public async Task DeleteSharedAccessPolicyAsync(string policyName,
  462. string containerName = null)
  463. {
  464. blobContainer = await CreateContainer(_options.Container);
  465. BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  466. permissions.SharedAccessPolicies.Remove(policyName);
  467. await blobContainer.SetPermissionsAsync(permissions);
  468. }
  469. /// <summary>
  470. ///为 blob 容器创建服务 SAS
  471. /// 若要为容器创建服务 SAS,请调用 CloudBlobContainer.GetSharedAccessSignature 方法。
  472. ///下面的代码示例在容器上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在容器上创建一个临时 SAS。
  473. /// </summary>
  474. /// <param name="container"></param>
  475. /// <param name="storedPolicyName"></param>
  476. /// <returns></returns>
  477. public async Task<(string, string, string)> GetContainerSasUri(string containerName = null, string storedPolicyName = null)
  478. {
  479. string sasContainerToken;
  480. blobContainer = await CreateContainer(_options.Container);
  481. // If no stored policy is specified, create a new access policy and define its constraints.
  482. if (storedPolicyName == null)
  483. {
  484. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  485. // to construct a shared access policy that is saved to the container's shared access policies.
  486. SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
  487. {
  488. // 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.
  489. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  490. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  491. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  492. Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create| SharedAccessBlobPermissions.Read
  493. };
  494. // Generate the shared access signature on the container, setting the constraints directly on the signature.
  495. sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  496. }
  497. else
  498. {
  499. // Generate the shared access signature on the container. In this case, all of the constraints for the
  500. // shared access signature are specified on the stored access policy, which is provided by name.
  501. // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
  502. sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
  503. }
  504. // Return the URI string for the container, including the SAS token.
  505. return (blobContainer.Uri.Scheme+ "://"+ blobContainer.Uri.Host.ToString() , blobContainer.Name, sasContainerToken);
  506. }
  507. public async Task<(string, string)> GetContainerSasUriRead(string containerName, string storedPolicyName = null)
  508. {
  509. string sasContainerToken;
  510. blobContainer = await CreateContainer(containerName);
  511. // If no stored policy is specified, create a new access policy and define its constraints.
  512. if (storedPolicyName == null)
  513. {
  514. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  515. // to construct a shared access policy that is saved to the container's shared access policies.
  516. SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
  517. {
  518. // 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.
  519. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  520. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  521. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
  522. Permissions = SharedAccessBlobPermissions.Read
  523. };
  524. // Generate the shared access signature on the container, setting the constraints directly on the signature.
  525. sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  526. }
  527. else
  528. {
  529. // Generate the shared access signature on the container. In this case, all of the constraints for the
  530. // shared access signature are specified on the stored access policy, which is provided by name.
  531. // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
  532. sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
  533. }
  534. // Return the URI string for the container, including the SAS token.
  535. return (blobContainer.Uri.ToString(), sasContainerToken);
  536. }
  537. /// <summary>
  538. /// 系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  539. /// "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  540. /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
  541. /// "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
  542. /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
  543. /// "teacher": [ "res", "item", "htex", "task", "info" ],
  544. /// 答案及学习活动上传的文件,学生基本信息关联
  545. ///"student": [ "stu/{studentId}/ans", "stu/{studentId}/task" ]
  546. /// </summary>
  547. /// <param name="name">容器名称</param>
  548. /// <param name="text">文件内容的流</param>
  549. /// <param name="folder">业务文件夹</param>
  550. /// <param name="fileName">文件名</param>
  551. /// <param name="contentTypeDefault">是否存放文件后缀对应的contentType</param>
  552. /// <returns></returns>
  553. public async Task<AzureBlobModel> UploadFileByContainer(string name ,string text, string folder, string fileName, bool contentTypeDefault = true)
  554. {
  555. // string groupName =folder;
  556. blobContainer = await CreateContainer(name.ToLower().Replace("#","")); //blobClient.GetContainerReference(groupName);
  557. StorageUri url = blobContainer.StorageUri;
  558. var blockBlob = blobContainer.GetBlockBlobReference(folder+"/"+fileName);
  559. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  560. string content_type = "application/octet-stream";
  561. if (!contentTypeDefault)
  562. {
  563. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  564. if (!string.IsNullOrEmpty(contenttype))
  565. {
  566. blockBlob.Properties.ContentType = contenttype;
  567. content_type = contenttype;
  568. }
  569. else
  570. {
  571. blockBlob.Properties.ContentType = content_type;
  572. }
  573. }
  574. else
  575. {
  576. blockBlob.Properties.ContentType = content_type;
  577. }
  578. await blockBlob.UploadTextAsync(text);
  579. byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
  580. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, folder, fileName, folder, blockBlob.Properties.ContentType, bytes.Length)
  581. {
  582. Sha1Code = ShaHashHelper.GetSHA1(bytes),
  583. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  584. };
  585. return model;
  586. }
  587. public async Task<dynamic> GetContainerSasUri(BlobSas blobSas, bool isRead)
  588. {
  589. CloudBlobContainer blobContainer;
  590. if (blobSas.role == "system")
  591. {
  592. blobContainer = await CreateContainer(_options.Container);
  593. }
  594. else
  595. {
  596. blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#", ""));
  597. }
  598. // If no stored policy is specified, create a new access policy and define its constraints.
  599. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  600. // to construct a shared access policy that is saved to the container's shared access policies.
  601. DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
  602. long time = dateTime.ToUnixTimeMilliseconds();
  603. SharedAccessBlobPolicy adHocPolicy = null;
  604. if (isRead)
  605. {
  606. adHocPolicy = new SharedAccessBlobPolicy()
  607. {
  608. // 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.
  609. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  610. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  611. SharedAccessExpiryTime = dateTime,
  612. Permissions = SharedAccessBlobPermissions.Read
  613. };
  614. }
  615. else {
  616. adHocPolicy = new SharedAccessBlobPolicy()
  617. {
  618. // 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.
  619. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  620. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  621. SharedAccessExpiryTime = dateTime,
  622. Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read| SharedAccessBlobPermissions.List
  623. };
  624. }
  625. // Generate the shared access signature on the container, setting the constraints directly on the signature.
  626. string sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
  627. return new { url = blobContainer.Uri, sas = sasContainerToken, timeout = time };
  628. }
  629. public async Task<Dictionary<string,object>> GetBlobSasUri(BlobSas blobSas,bool isRead) {
  630. string sasBlobToken;
  631. CloudBlobContainer blobContainer;
  632. if (blobSas.role == "system")
  633. {
  634. blobContainer = await CreateContainer(_options.Container);
  635. }
  636. else {
  637. blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#",""));
  638. }
  639. // Create a new access policy and define its constraints.
  640. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  641. // to construct a shared access policy that is saved to the container's shared access policies.
  642. DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
  643. SharedAccessBlobPolicy adHocSAS = null;
  644. if (isRead)
  645. {
  646. adHocSAS = new SharedAccessBlobPolicy()
  647. {
  648. // 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.
  649. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  650. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
  651. SharedAccessExpiryTime = dateTime,
  652. Permissions = SharedAccessBlobPermissions.Read
  653. };
  654. }
  655. else
  656. {
  657. adHocSAS = new SharedAccessBlobPolicy()
  658. {
  659. // 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.
  660. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  661. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
  662. SharedAccessExpiryTime = dateTime,
  663. Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
  664. };
  665. }
  666. Dictionary<string, object> dict = new Dictionary<string, object>();
  667. long time = dateTime.ToUnixTimeMilliseconds();
  668. List<string> folders = BaseConfigModel.Configuration.GetSection("Azure:Blob:" + blobSas.role).Get<List<string>>();
  669. if (folders.IsNotEmpty())
  670. {
  671. foreach (string floder in folders) {
  672. string cates = floder;
  673. if (blobSas.role == "student") {
  674. if (string.IsNullOrEmpty(blobSas.code)) {
  675. throw new BizException("请设置学生编码!", ResponseCode.PARAMS_ERROR);
  676. }
  677. cates = floder.Replace("{studentId}", blobSas.code);
  678. }
  679. // Get a reference to a blob within the container.
  680. // Note that the blob may not exist yet, but a SAS can still be created for it.
  681. CloudBlockBlob blob = blobContainer.GetBlockBlobReference(cates);
  682. // Generate the shared access signature on the blob, setting the constraints directly on the signature.
  683. sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  684. dict.Add(cates, new { url=blob.Uri,sas=sasBlobToken , timeout = time });
  685. }
  686. }
  687. return dict;
  688. }
  689. /// <summary>
  690. /// 若要为 blob 创建服务 SAS,请调用 CloudBlob.GetSharedAccessSignature 方法。
  691. ///下面的代码示例在 blob 上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在 Blob 上创建一个临时 SAS。
  692. /// </summary>
  693. /// <param name="container"></param>
  694. /// <param name="blobName"></param>
  695. /// <param name="policyName"></param>
  696. /// <returns></returns>
  697. public async Task<string> GetBlobSasUri(string blobName, string containerName=null, string policyName = null)
  698. {
  699. string sasBlobToken;
  700. blobContainer =await CreateContainer(_options.Container);
  701. // Get a reference to a blob within the container.
  702. // Note that the blob may not exist yet, but a SAS can still be created for it.
  703. CloudBlockBlob blob = blobContainer.GetBlockBlobReference( blobName );
  704. if (policyName == null)
  705. {
  706. // Create a new access policy and define its constraints.
  707. // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
  708. // to construct a shared access policy that is saved to the container's shared access policies.
  709. SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  710. {
  711. // 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.
  712. // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
  713. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  714. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  715. Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
  716. };
  717. // Generate the shared access signature on the blob, setting the constraints directly on the signature.
  718. sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  719. }
  720. else
  721. {
  722. // Generate the shared access signature on the blob. In this case, all of the constraints for the
  723. // shared access signature are specified on the container's stored access policy.
  724. sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
  725. }
  726. // Return the URI string for the container, including the SAS token.
  727. return blob.Uri + sasBlobToken;
  728. }
  729. public async Task<List<BlobFileDto>> GetBlobDirectory(string containerName, string blobName)
  730. {
  731. blobContainer = await CreateContainer(containerName);
  732. CloudBlobDirectory cloudBlobDirectory = blobContainer.GetDirectoryReference(blobName);
  733. List<BlobFileDto> blobProperties = new List<BlobFileDto>();
  734. blobProperties = GetBlobProperties(blobProperties, cloudBlobDirectory);
  735. return blobProperties;
  736. }
  737. public List<BlobFileDto> GetBlobProperties(List<BlobFileDto> blobProperties, CloudBlobDirectory blobDirectory)
  738. {
  739. IEnumerable<IListBlobItem> listBlobItems1 = blobDirectory.ListBlobsSegmentedAsync(new BlobContinuationToken()).GetAwaiter().GetResult().Results;
  740. foreach (IListBlobItem listBlobItem in listBlobItems1)
  741. {
  742. if (listBlobItem.GetType() == typeof(CloudBlobDirectory))
  743. {
  744. CloudBlobDirectory cloudBlobDirectory = (CloudBlobDirectory)listBlobItem;
  745. blobProperties = GetBlobProperties(blobProperties, cloudBlobDirectory);
  746. }
  747. else
  748. {
  749. CloudBlob blobaa = (CloudBlob)listBlobItem;
  750. blobaa.FetchAttributesAsync();
  751. BlobFileDto blobFileDto = new BlobFileDto
  752. {
  753. name = blobaa.Name,
  754. length = blobaa.Properties.Length,
  755. contentType = blobaa.Properties.ContentType,
  756. created = blobaa.Properties.Created != null ? blobaa.Properties.Created.Value.ToUnixTimeMilliseconds() : 0,//blobaa.Properties.Created.IsNull() ? 0 :
  757. lastModified = blobaa.Properties.LastModified != null ? blobaa.Properties.LastModified.Value.ToUnixTimeMilliseconds() : 0,//blobaa.Properties.LastModified.IsNull()? 0:
  758. url = blobaa.Uri.AbsoluteUri,
  759. BlobType = blobaa.BlobType.ToString()
  760. };
  761. blobProperties.Add(blobFileDto);
  762. }
  763. }
  764. return blobProperties;
  765. }
  766. public async Task<string> GetBlobSasUriRead(string containerName, string blobName, string policyName = null)
  767. {
  768. string sasBlobToken;
  769. blobContainer = await CreateContainer(containerName);
  770. CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
  771. if (policyName == null)
  772. {
  773. SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  774. {
  775. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  776. SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
  777. Permissions = SharedAccessBlobPermissions.Read
  778. };
  779. sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  780. }
  781. else
  782. {
  783. sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
  784. }
  785. return blob.Uri + sasBlobToken;
  786. }
  787. public async Task<dynamic> GetBlobSasUriRead(string containerName, string blobName)
  788. {
  789. string sasBlobToken;
  790. blobContainer = await GetContainer(containerName);
  791. CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
  792. DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
  793. long time = dateTime.ToUnixTimeMilliseconds();
  794. SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
  795. {
  796. SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
  797. SharedAccessExpiryTime = dateTime,
  798. Permissions = SharedAccessBlobPermissions.Read
  799. };
  800. sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
  801. return new { url = blob.Uri, sas = sasBlobToken, timeout = time };
  802. }
  803. private async Task<CloudBlobContainer> CreateContainer(string containerName)
  804. {
  805. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_options.ConnectionString);
  806. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  807. CloudBlobContainer container = blobClient.GetContainerReference(containerName);
  808. await container.CreateIfNotExistsAsync();
  809. return container;
  810. }
  811. private async Task<CloudBlobContainer> GetContainer(string containerName)
  812. {
  813. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_options.ConnectionString);
  814. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  815. CloudBlobContainer container = blobClient.GetContainerReference(containerName);
  816. bool a = await container.ExistsAsync();
  817. if (!a) {
  818. throw new BizException("容器不存在!",ResponseCode.PARAMS_ERROR);
  819. }
  820. // await container.CreateIfNotExistsAsync();
  821. return container;
  822. }
  823. public async Task Deleteblob(string azureBlobSAS)
  824. {
  825. (string, string) a = BlobUrlString(azureBlobSAS);
  826. string ContainerName = a.Item1;
  827. string BlobName = a.Item2;
  828. string PolicyName = "DeletePolicy";
  829. try
  830. {
  831. bool flg = await CreateSharedAccessPolicyAsync(PolicyName);
  832. if (flg)
  833. {
  834. string SAS = await GetBlobSasUri(BlobName, null, PolicyName);
  835. CloudBlockBlob blob = new CloudBlockBlob(new Uri(SAS));
  836. await blob.DeleteAsync();
  837. }
  838. // await DeleteSharedAccessPolicyAsync(PolicyName);
  839. }
  840. catch (Exception e) {
  841. throw new BizException(e.StackTrace);
  842. }
  843. finally {
  844. await DeleteSharedAccessPolicyAsync(PolicyName);
  845. }
  846. }
  847. private static (string, string) BlobUrlString(string sasUrl)
  848. {
  849. sasUrl = sasUrl.Substring(8);
  850. string[] sasUrls = sasUrl.Split("/");
  851. string ContainerName;
  852. ContainerName = sasUrls[1].Clone().ToString();
  853. string item = sasUrls[0] + "/" + sasUrls[1] + "/";
  854. string blob = sasUrl.Replace(item, "");
  855. return (ContainerName, blob);
  856. }
  857. }
  858. }