AzureBlobDBRepository.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 Microsoft.AspNetCore.Http.Internal;
  12. using TEAMModelOS.SDK.Helper.Security.AESCrypt;
  13. using TEAMModelOS.SDK.Context.Exception;
  14. using Microsoft.AspNetCore.Http;
  15. using System.Linq;
  16. using Microsoft.WindowsAzure.Storage.Shared.Protocol;
  17. using TEAMModelOS.SDK.Extension.SnowFlake;
  18. using TEAMModelOS.SDK.Context.Constant;
  19. using Microsoft.AspNetCore.StaticFiles;
  20. namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
  21. {
  22. public class AzureBlobDBRepository : IAzureBlobDBRepository
  23. {
  24. private readonly string china = "417A7572654368696E612020202020202020202020202020202020202020202097EB27FCC1F03349787DCD35F4DE22BBDFEDC90F24738B1D7FB9167A2C191BE671B512E17D48B73A002FC98867345CD59D3250AF59FD5FDFFC67976108F9E3BC9E9F75EDE605B058C1821D16BD9EB753B8E7D39FF48163430C1B5F3B6150195B880C3FCB87D35BF3540432734B768EC28C77B4CF0D556E794DE57979C1E01C429E66F7B2794D9940CF287F2B22A22E5F266B949D5E523E709FF37229E45D1A8FC8C4341E0A8346BB976CCB3D91802FFE5A4A28577898B4E942B5BA3A4A7B796FA673782D405060E7F2CBA4F67DF59F47";
  25. private readonly string global = "417A757265476C6F62616C2020202020202020202020202020202020202020206956019D195ED330AFA660D369B9464FC5E90AB3A106FDDD7978A2772DB186CDAE21C6CBFDE2B6739F089E853B3171A27841026E61C51666347F63FDF63E4377448D493B05CF6CDB3791946B9145825DD7756392EB8EA36DBF42E5C1C0021CEC2CDB5F4EA57EBCFA98B17D7236FA2CDCA6E7FCBE1DDC45BEAF691A2462A8BC3C429CBC4BCCA3192E554D23758AA8EA5937F988C927534C70A4769ED33878BEC10E2550F121E4AEB5A2DA213F2902D602A758C7D93D5DED368544F8A86D2A0CAA7813D1D950EC81D544EE41A8EDC84173";
  26. public CloudBlobClient blobClient;
  27. public CloudBlobContainer blobContainer;
  28. public AzureBlobOptions _options;
  29. public AzureBlobDBRepository(AzureBlobOptions options)
  30. {
  31. _options = options;
  32. if (!string.IsNullOrEmpty(options.ConnectionString))
  33. {
  34. blobClient = BlobClientSingleton.getInstance(options.ConnectionString).GetBlobClient();
  35. }
  36. else if (AzureBlobConfig.AZURE_CHINA.Equals(options.AzureTableDialect))
  37. {
  38. AESCrypt crypt = new AESCrypt();
  39. blobClient = BlobClientSingleton.getInstance(crypt.Decrypt(china, options.AzureTableDialect)).GetBlobClient();
  40. }
  41. else if (AzureBlobConfig.AZURE_GLOBAL.Equals(options.AzureTableDialect))
  42. {
  43. AESCrypt crypt = new AESCrypt();
  44. blobClient = BlobClientSingleton.getInstance(crypt.Decrypt(global, options.AzureTableDialect)).GetBlobClient();
  45. }
  46. else { throw new BizException("请设置正确的AzureBlob文件存储配置信息!"); }
  47. }
  48. public AzureBlobDBRepository()
  49. {
  50. // _connectionString = BaseConfigModel.Configuration["AppSettings:Azure:TableStorageConnection"];
  51. }
  52. //private async Task InitializeBlob(string container)
  53. //{
  54. ////https://teammodelstorage.blob.core.chinacloudapi.cn/wechatfilescontainer
  55. // if (blobContainer == null)
  56. // {
  57. // // Type t = typeof(T);
  58. // //若要将权限设置为仅针对 blob 的公共读取访问,请将 PublicAccess 属性设置为 BlobContainerPublicAccessType.Blob。
  59. // //要删除匿名用户的所有权限,请将该属性设置为 BlobContainerPublicAccessType.Off。
  60. // blobContainer = blobClient.GetContainerReference("wechatfilescontainer");
  61. // // await blobContainer.CreateIfNotExistsAsync();
  62. // // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  63. // // permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
  64. // // await blobContainer.SetPermissionsAsync(permissions);
  65. // }
  66. // //await UploadFiles(null, new FileContainer() );
  67. //}
  68. public async Task<List<AzureBlobModel>> UploadFiles(IFormFile[] file,string fileSpace="common")
  69. {
  70. string groupName = fileSpace+"/" +DateTime.Now.ToString("yyyyMMdd");
  71. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  72. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  73. blobContainer = blobClient.GetContainerReference( groupName);
  74. //var serviceProperties = await blobClient.GetServicePropertiesAsync();
  75. //var corsSettings = serviceProperties.Cors;
  76. //var corsRule = corsSettings.CorsRules.FirstOrDefault(
  77. // o => o.AllowedOrigins.Contains("http://localhost:3904"));//设置你自己的服务器地址
  78. //if (corsRule == null)
  79. //{
  80. // //Add a new rule.
  81. // corsRule = new CorsRule()
  82. // {
  83. // AllowedHeaders = new List<string> { "x-ms-*", "content-type", "accept" },
  84. // 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
  85. // AllowedOrigins = new List<string> { "http://localhost:3904" },//This is the URL of our application.
  86. // ExposedHeaders = { },
  87. // MaxAgeInSeconds = 1 * 60 * 60,//Let the browswer cache it for an hour
  88. // };
  89. // corsSettings.CorsRules.Add(corsRule);
  90. // //Save the rule
  91. // await blobClient.SetServicePropertiesAsync(serviceProperties);
  92. //}
  93. StorageUri url = blobContainer.StorageUri;
  94. List<AzureBlobModel> list = new List<AzureBlobModel>();
  95. foreach (FormFile f in file)
  96. {
  97. string[] names = f.FileName.Split(".");
  98. string name = "";
  99. for (int i = 0; i < names.Length-1; i++) {
  100. name = name + names[i];
  101. }
  102. if (names.Length <= 1)
  103. {
  104. name = f.FileName + "_" + newFileName;
  105. }
  106. else {
  107. name = name + "_" + newFileName + "." + names[names.Length - 1];
  108. }
  109. string fileext = f.FileName.Substring(f.FileName.LastIndexOf(".")>0? f.FileName.LastIndexOf("."):0);
  110. var parsedContentDisposition = ContentDispositionHeaderValue.Parse(f.ContentDisposition);
  111. var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  112. var blockBlob = blobContainer.GetBlockBlobReference(name);
  113. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  114. if (!string.IsNullOrEmpty(content_type))
  115. {
  116. blockBlob.Properties.ContentType = content_type;
  117. }
  118. await blockBlob.UploadFromStreamAsync(f.OpenReadStream());
  119. AzureBlobModel model = new AzureBlobModel(f, _options.Container, groupName, name)
  120. {
  121. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  122. };
  123. list.Add(model);
  124. }
  125. return list;
  126. }
  127. public async Task<AzureBlobModel> UploadPath(string path, string fileSpace = "common") {
  128. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  129. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  130. blobContainer = blobClient.GetContainerReference(groupName);
  131. StorageUri url = blobContainer.StorageUri;
  132. FileInfo file = new FileInfo(path);
  133. string[] names = file.Name.Split(".");
  134. string name = "";
  135. for (int i = 0; i < names.Length - 1; i++)
  136. {
  137. name = name + names[i];
  138. }
  139. if (names.Length <= 1)
  140. {
  141. name = file.Name + "_" + newFileName;
  142. }
  143. else
  144. {
  145. name = name + "_" + newFileName + "." + names[names.Length - 1];
  146. }
  147. string fileext = file.Name.Substring(file.Name.LastIndexOf(".") > 0 ? file.Name.LastIndexOf(".") : 0);
  148. var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  149. var blockBlob = blobContainer.GetBlockBlobReference(name);
  150. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  151. if (!string.IsNullOrEmpty(content_type))
  152. {
  153. blockBlob.Properties.ContentType = content_type;
  154. }
  155. else {
  156. content_type = "application/octet-stream";
  157. blockBlob.Properties.ContentType = content_type;
  158. }
  159. await blockBlob.UploadFromFileAsync(path);
  160. //var provider = new FileExtensionContentTypeProvider();
  161. //var memi = provider.Mappings[fileext];
  162. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name , content_type)
  163. {
  164. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  165. };
  166. return model;
  167. }
  168. public async Task<AzureBlobModel> UploadWord(IFormFile file, string fileSpace = "wordfiles")
  169. {
  170. long bizno= IdWorker.getInstance().NextId();
  171. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd")+"/"+ bizno;
  172. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  173. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  174. blobContainer = blobClient.GetContainerReference(groupName);
  175. StorageUri url = blobContainer.StorageUri;
  176. string[] names = file.FileName.Split(".");
  177. string name = "";
  178. for (int i = 0; i < names.Length - 1; i++)
  179. {
  180. name = name + names[i];
  181. }
  182. if (names.Length <= 1)
  183. {
  184. name = name + "_" + newFileName;
  185. }
  186. else
  187. {
  188. name = name + "_" + newFileName + "." + names[names.Length - 1];
  189. }
  190. var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  191. var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  192. var blockBlob = blobContainer.GetBlockBlobReference(name);
  193. await blockBlob.UploadFromStreamAsync(file.OpenReadStream());
  194. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name)
  195. {
  196. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  197. };
  198. return model;
  199. }
  200. }
  201. }