AzureBlobDBRepository.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
  18. {
  19. public class AzureBlobDBRepository : IAzureBlobDBRepository
  20. {
  21. private readonly string china = "417A7572654368696E612020202020202020202020202020202020202020202097EB27FCC1F03349787DCD35F4DE22BBDFEDC90F24738B1D7FB9167A2C191BE671B512E17D48B73A002FC98867345CD59D3250AF59FD5FDFFC67976108F9E3BC9E9F75EDE605B058C1821D16BD9EB753B8E7D39FF48163430C1B5F3B6150195B880C3FCB87D35BF3540432734B768EC28C77B4CF0D556E794DE57979C1E01C429E66F7B2794D9940CF287F2B22A22E5F266B949D5E523E709FF37229E45D1A8FC8C4341E0A8346BB976CCB3D91802FFE5A4A28577898B4E942B5BA3A4A7B796FA673782D405060E7F2CBA4F67DF59F47";
  22. private readonly string global = "417A757265476C6F62616C2020202020202020202020202020202020202020206956019D195ED330AFA660D369B9464FC5E90AB3A106FDDD7978A2772DB186CDAE21C6CBFDE2B6739F089E853B3171A27841026E61C51666347F63FDF63E4377448D493B05CF6CDB3791946B9145825DD7756392EB8EA36DBF42E5C1C0021CEC2CDB5F4EA57EBCFA98B17D7236FA2CDCA6E7FCBE1DDC45BEAF691A2462A8BC3C429CBC4BCCA3192E554D23758AA8EA5937F988C927534C70A4769ED33878BEC10E2550F121E4AEB5A2DA213F2902D602A758C7D93D5DED368544F8A86D2A0CAA7813D1D950EC81D544EE41A8EDC84173";
  23. public CloudBlobClient blobClient;
  24. public CloudBlobContainer blobContainer;
  25. public AzureBlobOptions _options;
  26. public AzureBlobDBRepository(AzureBlobOptions options)
  27. {
  28. _options = options;
  29. if (!string.IsNullOrEmpty(options.ConnectionString))
  30. {
  31. blobClient = BlobClientSingleton.getInstance(options.ConnectionString).GetBlobClient();
  32. }
  33. else if (AzureBlobConfig.AZURE_CHINA.Equals(options.AzureTableDialect))
  34. {
  35. AESCrypt crypt = new AESCrypt();
  36. blobClient = BlobClientSingleton.getInstance(crypt.Decrypt(china, options.AzureTableDialect)).GetBlobClient();
  37. }
  38. else if (AzureBlobConfig.AZURE_GLOBAL.Equals(options.AzureTableDialect))
  39. {
  40. AESCrypt crypt = new AESCrypt();
  41. blobClient = BlobClientSingleton.getInstance(crypt.Decrypt(global, options.AzureTableDialect)).GetBlobClient();
  42. }
  43. else { throw new BizException("请设置正确的AzureBlob文件存储配置信息!"); }
  44. }
  45. public AzureBlobDBRepository()
  46. {
  47. // _connectionString = BaseConfigModel.Configuration["AppSettings:Azure:TableStorageConnection"];
  48. }
  49. //private async Task InitializeBlob(string container)
  50. //{
  51. ////https://teammodelstorage.blob.core.chinacloudapi.cn/wechatfilescontainer
  52. // if (blobContainer == null)
  53. // {
  54. // // Type t = typeof(T);
  55. // //若要将权限设置为仅针对 blob 的公共读取访问,请将 PublicAccess 属性设置为 BlobContainerPublicAccessType.Blob。
  56. // //要删除匿名用户的所有权限,请将该属性设置为 BlobContainerPublicAccessType.Off。
  57. // blobContainer = blobClient.GetContainerReference("wechatfilescontainer");
  58. // // await blobContainer.CreateIfNotExistsAsync();
  59. // // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  60. // // permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
  61. // // await blobContainer.SetPermissionsAsync(permissions);
  62. // }
  63. // //await UploadFiles(null, new FileContainer() );
  64. //}
  65. public async Task<List<AzureBlobModel>> UploadFiles(IFormFile[] file,string fileSpace= "common" , bool contentTypeDefault = false)
  66. {
  67. string groupName = fileSpace+"/" +DateTime.Now.ToString("yyyyMMdd");
  68. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  69. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  70. blobContainer = blobClient.GetContainerReference( groupName);
  71. //var serviceProperties = await blobClient.GetServicePropertiesAsync();
  72. //var corsSettings = serviceProperties.Cors;
  73. //var corsRule = corsSettings.CorsRules.FirstOrDefault(
  74. // o => o.AllowedOrigins.Contains("http://localhost:3904"));//设置你自己的服务器地址
  75. //if (corsRule == null)
  76. //{
  77. // //Add a new rule.
  78. // corsRule = new CorsRule()
  79. // {
  80. // AllowedHeaders = new List<string> { "x-ms-*", "content-type", "accept" },
  81. // 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
  82. // AllowedOrigins = new List<string> { "http://localhost:3904" },//This is the URL of our application.
  83. // ExposedHeaders = { },
  84. // MaxAgeInSeconds = 1 * 60 * 60,//Let the browswer cache it for an hour
  85. // };
  86. // corsSettings.CorsRules.Add(corsRule);
  87. // //Save the rule
  88. // await blobClient.SetServicePropertiesAsync(serviceProperties);
  89. //}
  90. StorageUri url = blobContainer.StorageUri;
  91. List<AzureBlobModel> list = new List<AzureBlobModel>();
  92. foreach (FormFile f in file)
  93. {
  94. string[] names = f.FileName.Split(".");
  95. string name = "";
  96. for (int i = 0; i < names.Length-1; i++) {
  97. name = name + names[i];
  98. }
  99. if (names.Length <= 1)
  100. {
  101. name = f.FileName + "_" + newFileName;
  102. }
  103. else {
  104. name = name + "_" + newFileName + "." + names[names.Length - 1];
  105. }
  106. string fileext = f.FileName.Substring(f.FileName.LastIndexOf(".")>0? f.FileName.LastIndexOf("."):0);
  107. var parsedContentDisposition = ContentDispositionHeaderValue.Parse(f.ContentDisposition);
  108. var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  109. var blockBlob = blobContainer.GetBlockBlobReference(name);
  110. if (!contentTypeDefault) {
  111. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  112. if (!string.IsNullOrEmpty(content_type))
  113. {
  114. blockBlob.Properties.ContentType = content_type;
  115. }
  116. }
  117. await blockBlob.UploadFromStreamAsync(f.OpenReadStream());
  118. AzureBlobModel model = new AzureBlobModel(f, _options.Container, groupName, name)
  119. {
  120. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  121. };
  122. list.Add(model);
  123. }
  124. return list;
  125. }
  126. public async Task<AzureBlobModel> UploadPath(string path, string fileSpace = "common" , bool contentTypeDefault = false) {
  127. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  128. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  129. blobContainer = blobClient.GetContainerReference(groupName);
  130. StorageUri url = blobContainer.StorageUri;
  131. FileInfo file = new FileInfo(path);
  132. string[] names = file.Name.Split(".");
  133. string name = "";
  134. for (int i = 0; i < names.Length - 1; i++)
  135. {
  136. name = name + names[i];
  137. }
  138. if (names.Length <= 1)
  139. {
  140. name = file.Name + "_" + newFileName;
  141. }
  142. else
  143. {
  144. name = name + "_" + newFileName + "." + names[names.Length - 1];
  145. }
  146. string fileext = file.Name.Substring(file.Name.LastIndexOf(".") > 0 ? file.Name.LastIndexOf(".") : 0);
  147. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  148. var blockBlob = blobContainer.GetBlockBlobReference(name);
  149. string content_type = "application/octet-stream";
  150. if (!contentTypeDefault)
  151. {
  152. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  153. if (!string.IsNullOrEmpty(contenttype))
  154. {
  155. blockBlob.Properties.ContentType = contenttype;
  156. content_type = contenttype;
  157. }
  158. else
  159. {
  160. blockBlob.Properties.ContentType = content_type;
  161. }
  162. }
  163. else
  164. {
  165. blockBlob.Properties.ContentType = content_type;
  166. }
  167. await blockBlob.UploadFromFileAsync(path);
  168. //var provider = new FileExtensionContentTypeProvider();
  169. //var memi = provider.Mappings[fileext];
  170. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name , content_type)
  171. {
  172. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  173. };
  174. return model;
  175. }
  176. public async Task<AzureBlobModel> UploadText(string fileName, string text, string fileSpace = "common", bool contentTypeDefault = true)
  177. {
  178. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  179. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  180. blobContainer = blobClient.GetContainerReference(groupName);
  181. StorageUri url = blobContainer.StorageUri;
  182. //FileInfo file = new FileInfo(path);
  183. string[] names = fileName.Split(".");
  184. string name = "";
  185. for (int i = 0; i < names.Length - 1; i++)
  186. {
  187. name = name + names[i];
  188. }
  189. if (names.Length <= 1)
  190. {
  191. name = fileName + "_" + newFileName;
  192. }
  193. else
  194. {
  195. name = name + "_" + newFileName + "." + names[names.Length - 1];
  196. }
  197. var blockBlob = blobContainer.GetBlockBlobReference(name);
  198. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  199. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  200. string content_type = "application/octet-stream";
  201. if (!contentTypeDefault)
  202. {
  203. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  204. if (!string.IsNullOrEmpty(contenttype))
  205. {
  206. blockBlob.Properties.ContentType = contenttype;
  207. content_type = contenttype;
  208. }
  209. else
  210. {
  211. blockBlob.Properties.ContentType = content_type;
  212. }
  213. }
  214. else
  215. {
  216. blockBlob.Properties.ContentType = content_type;
  217. }
  218. long length = System.Text.Encoding.Default.GetBytes(text).Length;
  219. await blockBlob.UploadTextAsync(text);
  220. //var provider = new FileExtensionContentTypeProvider();
  221. //var memi = provider.Mappings[fileext];
  222. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type, length)
  223. {
  224. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  225. };
  226. return model;
  227. }
  228. public async Task<AzureBlobModel> UploadObject(string fileName,object obj, string fileSpace = "common", bool contentTypeDefault =true)
  229. {
  230. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  231. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  232. blobContainer = blobClient.GetContainerReference(groupName);
  233. StorageUri url = blobContainer.StorageUri;
  234. //FileInfo file = new FileInfo(path);
  235. string[] names = fileName.Split(".");
  236. string name = "";
  237. for (int i = 0; i < names.Length - 1; i++)
  238. {
  239. name = name + names[i];
  240. }
  241. if (names.Length <= 1)
  242. {
  243. name = fileName + "_" + newFileName;
  244. }
  245. else
  246. {
  247. name = name + "_" + newFileName + "." + names[names.Length - 1];
  248. }
  249. var blockBlob = blobContainer.GetBlockBlobReference(name);
  250. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  251. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  252. string content_type = "application/octet-stream";
  253. if (!contentTypeDefault)
  254. {
  255. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  256. if (!string.IsNullOrEmpty(contenttype))
  257. {
  258. blockBlob.Properties.ContentType = contenttype;
  259. content_type = contenttype;
  260. }
  261. else
  262. {
  263. blockBlob.Properties.ContentType = content_type;
  264. }
  265. }
  266. else {
  267. blockBlob.Properties.ContentType = content_type;
  268. }
  269. string objStr = obj.ToJsonAbs();
  270. long length = System.Text.Encoding.Default.GetBytes(objStr).Length;
  271. await blockBlob.UploadTextAsync(objStr);
  272. //var provider = new FileExtensionContentTypeProvider();
  273. //var memi = provider.Mappings[fileext];
  274. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type , length)
  275. {
  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 = 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. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name)
  316. {
  317. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  318. };
  319. return model;
  320. }
  321. public AzureBlobModel UploadFileByFolderNAsyn(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  322. {
  323. string groupName = fileSpace + "/" + folder;
  324. // string newFileName = sha1Code;
  325. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  326. blobContainer = blobClient.GetContainerReference(groupName);
  327. StorageUri url = blobContainer.StorageUri;
  328. string[] names = fileName.Split(".");
  329. // string name ;
  330. //for (int i = 0; i < names.Length - 1; i++)
  331. //{
  332. // name = name + names[i];
  333. //}
  334. //if (names.Length <= 1)
  335. //{
  336. // name = newFileName;
  337. //}
  338. //else
  339. //{
  340. // name = newFileName + "." + names[names.Length - 1];
  341. //}
  342. //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  343. //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  344. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  345. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  346. if (!contentTypeDefault)
  347. {
  348. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  349. if (!string.IsNullOrEmpty(content_type))
  350. {
  351. blockBlob.Properties.ContentType = content_type;
  352. }
  353. else
  354. {
  355. blockBlob.Properties.ContentType = "application/octet-stream";
  356. }
  357. }
  358. blockBlob.UploadFromStreamAsync(fileSteam).GetAwaiter().GetResult() ;
  359. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
  360. {
  361. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  362. };
  363. return model;
  364. }
  365. public async Task<AzureBlobModel> UploadFileByFolder(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  366. {
  367. string groupName = fileSpace + "/" + folder;
  368. // string newFileName = sha1Code;
  369. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  370. blobContainer = blobClient.GetContainerReference(groupName);
  371. StorageUri url = blobContainer.StorageUri;
  372. string[] names = fileName.Split(".");
  373. // string name ;
  374. //for (int i = 0; i < names.Length - 1; i++)
  375. //{
  376. // name = name + names[i];
  377. //}
  378. //if (names.Length <= 1)
  379. //{
  380. // name = newFileName;
  381. //}
  382. //else
  383. //{
  384. // name = newFileName + "." + names[names.Length - 1];
  385. //}
  386. //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  387. //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  388. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  389. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  390. if (!contentTypeDefault)
  391. {
  392. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  393. if (!string.IsNullOrEmpty(content_type))
  394. {
  395. blockBlob.Properties.ContentType = content_type;
  396. }
  397. else {
  398. blockBlob.Properties.ContentType = "application/octet-stream";
  399. }
  400. }
  401. await blockBlob.UploadFromStreamAsync(fileSteam);
  402. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType , fileSteam.Length)
  403. {
  404. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  405. };
  406. return model;
  407. }
  408. public async Task<AzureBlobModel> UploadTextByFolder(string text, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
  409. {
  410. string groupName = fileSpace + "/" + folder;
  411. blobContainer = blobClient.GetContainerReference(groupName);
  412. StorageUri url = blobContainer.StorageUri;
  413. var blockBlob = blobContainer.GetBlockBlobReference(fileName);
  414. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  415. string content_type = "application/octet-stream";
  416. if (!contentTypeDefault)
  417. {
  418. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  419. if (!string.IsNullOrEmpty(contenttype))
  420. {
  421. blockBlob.Properties.ContentType = contenttype;
  422. content_type = contenttype;
  423. }
  424. else
  425. {
  426. blockBlob.Properties.ContentType = content_type;
  427. }
  428. }
  429. else
  430. {
  431. blockBlob.Properties.ContentType = content_type;
  432. }
  433. long length = System.Text.Encoding.Default.GetBytes(text).Length;
  434. await blockBlob.UploadTextAsync(text);
  435. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, length)
  436. {
  437. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
  438. };
  439. return model;
  440. }
  441. }
  442. }