AzureBlobDBRepository.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. using System.Runtime.Serialization.Formatters.Binary;
  21. using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  22. namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
  23. {
  24. public class AzureBlobDBRepository : IAzureBlobDBRepository
  25. {
  26. private readonly string china = "417A7572654368696E612020202020202020202020202020202020202020202097EB27FCC1F03349787DCD35F4DE22BBDFEDC90F24738B1D7FB9167A2C191BE671B512E17D48B73A002FC98867345CD59D3250AF59FD5FDFFC67976108F9E3BC9E9F75EDE605B058C1821D16BD9EB753B8E7D39FF48163430C1B5F3B6150195B880C3FCB87D35BF3540432734B768EC28C77B4CF0D556E794DE57979C1E01C429E66F7B2794D9940CF287F2B22A22E5F266B949D5E523E709FF37229E45D1A8FC8C4341E0A8346BB976CCB3D91802FFE5A4A28577898B4E942B5BA3A4A7B796FA673782D405060E7F2CBA4F67DF59F47";
  27. private readonly string global = "417A757265476C6F62616C2020202020202020202020202020202020202020206956019D195ED330AFA660D369B9464FC5E90AB3A106FDDD7978A2772DB186CDAE21C6CBFDE2B6739F089E853B3171A27841026E61C51666347F63FDF63E4377448D493B05CF6CDB3791946B9145825DD7756392EB8EA36DBF42E5C1C0021CEC2CDB5F4EA57EBCFA98B17D7236FA2CDCA6E7FCBE1DDC45BEAF691A2462A8BC3C429CBC4BCCA3192E554D23758AA8EA5937F988C927534C70A4769ED33878BEC10E2550F121E4AEB5A2DA213F2902D602A758C7D93D5DED368544F8A86D2A0CAA7813D1D950EC81D544EE41A8EDC84173";
  28. public CloudBlobClient blobClient;
  29. public CloudBlobContainer blobContainer;
  30. public AzureBlobOptions _options;
  31. public AzureBlobDBRepository(AzureBlobOptions options)
  32. {
  33. _options = options;
  34. if (!string.IsNullOrEmpty(options.ConnectionString))
  35. {
  36. blobClient = BlobClientSingleton.getInstance(options.ConnectionString).GetBlobClient();
  37. }
  38. else if (AzureBlobConfig.AZURE_CHINA.Equals(options.AzureTableDialect))
  39. {
  40. AESCrypt crypt = new AESCrypt();
  41. blobClient = BlobClientSingleton.getInstance(crypt.Decrypt(china, options.AzureTableDialect)).GetBlobClient();
  42. }
  43. else if (AzureBlobConfig.AZURE_GLOBAL.Equals(options.AzureTableDialect))
  44. {
  45. AESCrypt crypt = new AESCrypt();
  46. blobClient = BlobClientSingleton.getInstance(crypt.Decrypt(global, options.AzureTableDialect)).GetBlobClient();
  47. }
  48. else { throw new BizException("请设置正确的AzureBlob文件存储配置信息!"); }
  49. }
  50. public AzureBlobDBRepository()
  51. {
  52. // _connectionString = BaseConfigModel.Configuration["AppSettings:Azure:TableStorageConnection"];
  53. }
  54. //private async Task InitializeBlob(string container)
  55. //{
  56. ////https://teammodelstorage.blob.core.chinacloudapi.cn/wechatfilescontainer
  57. // if (blobContainer == null)
  58. // {
  59. // // Type t = typeof(T);
  60. // //若要将权限设置为仅针对 blob 的公共读取访问,请将 PublicAccess 属性设置为 BlobContainerPublicAccessType.Blob。
  61. // //要删除匿名用户的所有权限,请将该属性设置为 BlobContainerPublicAccessType.Off。
  62. // blobContainer = blobClient.GetContainerReference("wechatfilescontainer");
  63. // // await blobContainer.CreateIfNotExistsAsync();
  64. // // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
  65. // // permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
  66. // // await blobContainer.SetPermissionsAsync(permissions);
  67. // }
  68. // //await UploadFiles(null, new FileContainer() );
  69. //}
  70. public async Task<List<AzureBlobModel>> UploadFiles(IFormFile[] file,string fileSpace= "common" , bool contentTypeDefault = false)
  71. {
  72. string groupName = fileSpace+"/" +DateTime.Now.ToString("yyyyMMdd");
  73. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  74. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  75. blobContainer = blobClient.GetContainerReference( groupName);
  76. //var serviceProperties = await blobClient.GetServicePropertiesAsync();
  77. //var corsSettings = serviceProperties.Cors;
  78. //var corsRule = corsSettings.CorsRules.FirstOrDefault(
  79. // o => o.AllowedOrigins.Contains("http://localhost:3904"));//设置你自己的服务器地址
  80. //if (corsRule == null)
  81. //{
  82. // //Add a new rule.
  83. // corsRule = new CorsRule()
  84. // {
  85. // AllowedHeaders = new List<string> { "x-ms-*", "content-type", "accept" },
  86. // 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
  87. // AllowedOrigins = new List<string> { "http://localhost:3904" },//This is the URL of our application.
  88. // ExposedHeaders = { },
  89. // MaxAgeInSeconds = 1 * 60 * 60,//Let the browswer cache it for an hour
  90. // };
  91. // corsSettings.CorsRules.Add(corsRule);
  92. // //Save the rule
  93. // await blobClient.SetServicePropertiesAsync(serviceProperties);
  94. //}
  95. StorageUri url = blobContainer.StorageUri;
  96. List<AzureBlobModel> list = new List<AzureBlobModel>();
  97. foreach (FormFile f in file)
  98. {
  99. string[] names = f.FileName.Split(".");
  100. string name = "";
  101. for (int i = 0; i < names.Length-1; i++) {
  102. name = name + names[i];
  103. }
  104. if (names.Length <= 1)
  105. {
  106. name = f.FileName + "_" + newFileName;
  107. }
  108. else {
  109. name = name + "_" + newFileName + "." + names[names.Length - 1];
  110. }
  111. string fileext = f.FileName.Substring(f.FileName.LastIndexOf(".")>0? f.FileName.LastIndexOf("."):0);
  112. var parsedContentDisposition = ContentDispositionHeaderValue.Parse(f.ContentDisposition);
  113. var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  114. var blockBlob = blobContainer.GetBlockBlobReference(name);
  115. if (!contentTypeDefault) {
  116. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  117. if (!string.IsNullOrEmpty(content_type))
  118. {
  119. blockBlob.Properties.ContentType = content_type;
  120. }
  121. }
  122. await blockBlob.UploadFromStreamAsync(f.OpenReadStream());
  123. AzureBlobModel model = new AzureBlobModel(f, _options.Container, groupName, name)
  124. {
  125. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  126. };
  127. list.Add(model);
  128. }
  129. return list;
  130. }
  131. public async Task<AzureBlobModel> UploadPath(string path, string fileSpace = "common" , bool contentTypeDefault = false) {
  132. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  133. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  134. blobContainer = blobClient.GetContainerReference(groupName);
  135. StorageUri url = blobContainer.StorageUri;
  136. FileInfo file = new FileInfo(path);
  137. string[] names = file.Name.Split(".");
  138. string name = "";
  139. for (int i = 0; i < names.Length - 1; i++)
  140. {
  141. name = name + names[i];
  142. }
  143. if (names.Length <= 1)
  144. {
  145. name = file.Name + "_" + newFileName;
  146. }
  147. else
  148. {
  149. name = name + "_" + newFileName + "." + names[names.Length - 1];
  150. }
  151. string fileext = file.Name.Substring(file.Name.LastIndexOf(".") > 0 ? file.Name.LastIndexOf(".") : 0);
  152. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  153. var blockBlob = blobContainer.GetBlockBlobReference(name);
  154. string content_type = "application/octet-stream";
  155. if (!contentTypeDefault)
  156. {
  157. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  158. if (!string.IsNullOrEmpty(contenttype))
  159. {
  160. blockBlob.Properties.ContentType = contenttype;
  161. content_type = contenttype;
  162. }
  163. else
  164. {
  165. blockBlob.Properties.ContentType = content_type;
  166. }
  167. }
  168. else
  169. {
  170. blockBlob.Properties.ContentType = content_type;
  171. }
  172. await blockBlob.UploadFromFileAsync(path);
  173. //var provider = new FileExtensionContentTypeProvider();
  174. //var memi = provider.Mappings[fileext];
  175. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name , content_type)
  176. {
  177. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  178. };
  179. return model;
  180. }
  181. public async Task<AzureBlobModel> UploadText(string fileName, string text, string fileSpace = "common", bool contentTypeDefault = true)
  182. {
  183. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  184. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  185. blobContainer = blobClient.GetContainerReference(groupName);
  186. StorageUri url = blobContainer.StorageUri;
  187. //FileInfo file = new FileInfo(path);
  188. string[] names = fileName.Split(".");
  189. string name = "";
  190. for (int i = 0; i < names.Length - 1; i++)
  191. {
  192. name = name + names[i];
  193. }
  194. if (names.Length <= 1)
  195. {
  196. name = fileName + "_" + newFileName;
  197. }
  198. else
  199. {
  200. name = name + "_" + newFileName + "." + names[names.Length - 1];
  201. }
  202. var blockBlob = blobContainer.GetBlockBlobReference(name);
  203. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  204. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  205. string content_type = "application/octet-stream";
  206. if (!contentTypeDefault)
  207. {
  208. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  209. if (!string.IsNullOrEmpty(contenttype))
  210. {
  211. blockBlob.Properties.ContentType = contenttype;
  212. content_type = contenttype;
  213. }
  214. else
  215. {
  216. blockBlob.Properties.ContentType = content_type;
  217. }
  218. }
  219. else
  220. {
  221. blockBlob.Properties.ContentType = content_type;
  222. }
  223. long length = System.Text.Encoding.Default.GetBytes(text).Length;
  224. await blockBlob.UploadTextAsync(text);
  225. //var provider = new FileExtensionContentTypeProvider();
  226. //var memi = provider.Mappings[fileext];
  227. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type, length)
  228. {
  229. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  230. };
  231. return model;
  232. }
  233. public async Task<AzureBlobModel> UploadObject(string fileName,object obj, string fileSpace = "common", bool contentTypeDefault =true)
  234. {
  235. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
  236. string newFileName = DateTime.Now.ToString("HHmmssfffffff");
  237. blobContainer = blobClient.GetContainerReference(groupName);
  238. StorageUri url = blobContainer.StorageUri;
  239. //FileInfo file = new FileInfo(path);
  240. string[] names = fileName.Split(".");
  241. string name = "";
  242. for (int i = 0; i < names.Length - 1; i++)
  243. {
  244. name = name + names[i];
  245. }
  246. if (names.Length <= 1)
  247. {
  248. name = fileName + "_" + newFileName;
  249. }
  250. else
  251. {
  252. name = name + "_" + newFileName + "." + names[names.Length - 1];
  253. }
  254. var blockBlob = blobContainer.GetBlockBlobReference(name);
  255. // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
  256. string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
  257. string content_type = "application/octet-stream";
  258. if (!contentTypeDefault)
  259. {
  260. ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
  261. if (!string.IsNullOrEmpty(contenttype))
  262. {
  263. blockBlob.Properties.ContentType = contenttype;
  264. content_type = contenttype;
  265. }
  266. else
  267. {
  268. blockBlob.Properties.ContentType = content_type;
  269. }
  270. }
  271. else {
  272. blockBlob.Properties.ContentType = content_type;
  273. }
  274. string objStr = obj.ToJsonAbs();
  275. long length = System.Text.Encoding.Default.GetBytes(objStr).Length;
  276. await blockBlob.UploadTextAsync(objStr);
  277. //var provider = new FileExtensionContentTypeProvider();
  278. //var memi = provider.Mappings[fileext];
  279. AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type , length)
  280. {
  281. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  282. };
  283. return model;
  284. }
  285. public async Task<AzureBlobModel> UploadFile(IFormFile file, string fileSpace = "wordfiles", bool contentTypeDefault = true)
  286. {
  287. long bizno= IdWorker.getInstance().NextId();
  288. string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd")+"/"+ bizno;
  289. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
  290. // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
  291. blobContainer = blobClient.GetContainerReference(groupName);
  292. StorageUri url = blobContainer.StorageUri;
  293. string[] names = file.FileName.Split(".");
  294. string name = "";
  295. for (int i = 0; i < names.Length - 1; i++)
  296. {
  297. name = name + names[i];
  298. }
  299. if (names.Length <= 1)
  300. {
  301. name = name + "_" + newFileName;
  302. }
  303. else
  304. {
  305. name = name + "_" + newFileName + "." + names[names.Length - 1];
  306. }
  307. var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
  308. var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
  309. var blockBlob = blobContainer.GetBlockBlobReference(name);
  310. string fileext = filename.Substring(filename.LastIndexOf(".") > 0 ? filename.LastIndexOf(".") : 0);
  311. if (!contentTypeDefault)
  312. {
  313. ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
  314. if (!string.IsNullOrEmpty(content_type))
  315. {
  316. blockBlob.Properties.ContentType = content_type;
  317. }
  318. }
  319. await blockBlob.UploadFromStreamAsync(file.OpenReadStream());
  320. AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name)
  321. {
  322. BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
  323. };
  324. return model;
  325. }
  326. }
  327. }