123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862 |
- using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
- using TEAMModelOS.SDK.Module.AzureBlob.Container;
- using TEAMModelOS.SDK.Module.AzureBlob.Interfaces;
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Blob;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- using TEAMModelOS.SDK.Helper.Security.AESCrypt;
- using TEAMModelOS.SDK.Context.Exception;
- using Microsoft.AspNetCore.Http;
- using TEAMModelOS.SDK.Extension.SnowFlake;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.Helper.Common.JsonHelper;
- using TEAMModelOS.SDK.Helper.Security.ShaHash;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.SDK.Context.Configuration;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Azure.Cosmos.Linq;
- using System.Reflection.Metadata;
- using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
- using Jaeger.Util;
- namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
- {
- public class AzureBlobDBRepository : IAzureBlobDBRepository
- {
- public CloudBlobClient blobClient;
- public CloudBlobContainer blobContainer;
- public AzureBlobOptions _options;
- public IConfiguration Configuration { get; }
- public AzureBlobDBRepository(IConfiguration configuration, IWebHostEnvironment env, AzureBlobOptions options, AzureBlobOptions azureBlobOptions)
- {
- Configuration = configuration;
- // BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
- _options = options;
- if (!string.IsNullOrEmpty(options.ConnectionString))
- {
- blobClient = BlobClientSingleton.getInstance(options.ConnectionString).GetBlobClient();
- }
- else { throw new BizException("请设置正确的AzureBlob文件存储配置信息!"); }
- }
- public AzureBlobDBRepository()
- {
-
- }
- private CloudBlobContainer InitializeBlob(string container)
- {
- //https://teammodelstorage.blob.core.chinacloudapi.cn/wechatfilescontainer
-
- // Type t = typeof(T);
- //若要将权限设置为仅针对 blob 的公共读取访问,请将 PublicAccess 属性设置为 BlobContainerPublicAccessType.Blob。
- //要删除匿名用户的所有权限,请将该属性设置为 BlobContainerPublicAccessType.Off。
- blobContainer = blobClient.GetContainerReference(_options .Container+"/"+ container);
- // await blobContainer.CreateIfNotExistsAsync();
- // BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
- // permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
- // await blobContainer.SetPermissionsAsync(permissions);
-
- return blobContainer;
- }
- public async Task<List<AzureBlobModel>> UploadFiles(IFormFile[] file,string fileSpace= "common" , bool contentTypeDefault = false)
- {
- string groupName = fileSpace+"/" +DateTime.Now.ToString("yyyyMMdd");
- string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
- // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- //var serviceProperties = await blobClient.GetServicePropertiesAsync();
- //var corsSettings = serviceProperties.Cors;
- //var corsRule = corsSettings.CorsRules.FirstOrDefault(
- // o => o.AllowedOrigins.Contains("http://localhost:3904"));//设置你自己的服务器地址
- //if (corsRule == null)
- //{
- // //Add a new rule.
- // corsRule = new CorsRule()
- // {
- // AllowedHeaders = new List<string> { "x-ms-*", "content-type", "accept" },
- // 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
- // AllowedOrigins = new List<string> { "http://localhost:3904" },//This is the URL of our application.
- // ExposedHeaders = { },
- // MaxAgeInSeconds = 1 * 60 * 60,//Let the browswer cache it for an hour
- // };
- // corsSettings.CorsRules.Add(corsRule);
- // //Save the rule
- // await blobClient.SetServicePropertiesAsync(serviceProperties);
- //}
- StorageUri url = blobContainer.StorageUri;
- List<AzureBlobModel> list = new List<AzureBlobModel>();
- foreach (FormFile f in file)
- {
-
- string[] names = f.FileName.Split(".");
- string name = "";
- for (int i = 0; i < names.Length-1; i++) {
- name = name + names[i];
- }
- if (names.Length <= 1)
- {
- name = f.FileName + "_" + newFileName;
- }
- else {
- name = name + "_" + newFileName + "." + names[names.Length - 1];
- }
- string fileext = f.FileName.Substring(f.FileName.LastIndexOf(".")>0? f.FileName.LastIndexOf("."):0);
-
- var parsedContentDisposition = ContentDispositionHeaderValue.Parse(f.ContentDisposition);
- var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
- var blockBlob = blobContainer.GetBlockBlobReference(name);
- if (!contentTypeDefault) {
- ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
- if (!string.IsNullOrEmpty(content_type))
- {
- blockBlob.Properties.ContentType = content_type;
- }
- }
- await blockBlob.UploadFromStreamAsync(f.OpenReadStream());
- string sha1= ShaHashHelper.GetSHA1(f.OpenReadStream());
- AzureBlobModel model = new AzureBlobModel(f, _options.Container, groupName, name)
- {
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name,
- Sha1Code = sha1
- };
- list.Add(model);
- }
- return list;
- }
- public async Task<AzureBlobModel> UploadPath(string path, string fileSpace = "common" , bool contentTypeDefault = false) {
- string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
- string newFileName = DateTime.Now.ToString("HHmmssfffffff");
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- StorageUri url = blobContainer.StorageUri;
- FileInfo file = new FileInfo(path);
- string[] names = file.Name.Split(".");
- string name = "";
- for (int i = 0; i < names.Length - 1; i++)
- {
- name = name + names[i];
- }
- if (names.Length <= 1)
- {
- name = file.Name + "_" + newFileName;
- }
- else
- {
- name = name + "_" + newFileName + "." + names[names.Length - 1];
- }
- string fileext = file.Name.Substring(file.Name.LastIndexOf(".") > 0 ? file.Name.LastIndexOf(".") : 0);
- // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
- var blockBlob = blobContainer.GetBlockBlobReference(name);
- string content_type = "application/octet-stream";
- if (!contentTypeDefault)
- {
- ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
- if (!string.IsNullOrEmpty(contenttype))
- {
- blockBlob.Properties.ContentType = contenttype;
- content_type = contenttype;
- }
- else
- {
- blockBlob.Properties.ContentType = content_type;
- }
- }
- else
- {
- blockBlob.Properties.ContentType = content_type;
- }
- await blockBlob.UploadFromFileAsync(path);
- //var provider = new FileExtensionContentTypeProvider();
- //var memi = provider.Mappings[fileext];
- AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name , content_type)
- {
- Sha1Code=ShaHashHelper.GetSHA1(file.Create()),
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
- };
- return model;
- }
- public async Task<AzureBlobModel> UploadText(string fileName, string text, string fileSpace = "common", bool contentTypeDefault = true)
- {
- string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
- string newFileName = DateTime.Now.ToString("HHmmssfffffff");
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- StorageUri url = blobContainer.StorageUri;
- //FileInfo file = new FileInfo(path);
- string[] names = fileName.Split(".");
- string name = "";
- for (int i = 0; i < names.Length - 1; i++)
- {
- name = name + names[i];
- }
- if (names.Length <= 1)
- {
- name = fileName + "_" + newFileName;
- }
- else
- {
- name = name + "_" + newFileName + "." + names[names.Length - 1];
- }
- var blockBlob = blobContainer.GetBlockBlobReference(name);
- // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
- string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
- string content_type = "application/octet-stream";
- if (!contentTypeDefault)
- {
- ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
- if (!string.IsNullOrEmpty(contenttype))
- {
- blockBlob.Properties.ContentType = contenttype;
- content_type = contenttype;
- }
- else
- {
- blockBlob.Properties.ContentType = content_type;
- }
- }
- else
- {
- blockBlob.Properties.ContentType = content_type;
- }
-
-
- await blockBlob.UploadTextAsync(text);
- byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
- //var provider = new FileExtensionContentTypeProvider();
- //var memi = provider.Mappings[fileext];
- AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type, bytes.Length)
- {
- Sha1Code = ShaHashHelper.GetSHA1(bytes),
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
- };
- return model;
- }
- public async Task<AzureBlobModel> UploadObject(string fileName,object obj, string fileSpace = "common", bool contentTypeDefault =true)
- {
- string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd");
- string newFileName = DateTime.Now.ToString("HHmmssfffffff");
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- StorageUri url = blobContainer.StorageUri;
- //FileInfo file = new FileInfo(path);
- string[] names = fileName.Split(".");
- string name = "";
- for (int i = 0; i < names.Length - 1; i++)
- {
- name = name + names[i];
- }
- if (names.Length <= 1)
- {
- name = fileName + "_" + newFileName;
- }
- else
- {
- name = name + "_" + newFileName + "." + names[names.Length - 1];
- }
- var blockBlob = blobContainer.GetBlockBlobReference(name);
- // var parsedContentDisposition = ContentDispositionHeaderValue.Parse("form-data; name=\"files\"; filename=\"" + file.Name + "\"");
- string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
- string content_type = "application/octet-stream";
- if (!contentTypeDefault)
- {
- ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
- if (!string.IsNullOrEmpty(contenttype))
- {
- blockBlob.Properties.ContentType = contenttype;
- content_type = contenttype;
- }
- else
- {
- blockBlob.Properties.ContentType = content_type;
- }
- }
- else {
- blockBlob.Properties.ContentType = content_type;
- }
- string objStr = obj.ToJsonAbs();
-
- await blockBlob.UploadTextAsync(objStr);
- //var provider = new FileExtensionContentTypeProvider();
- //var memi = provider.Mappings[fileext];
- byte[] bytes = System.Text.Encoding.Default.GetBytes(objStr);
- AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, name, content_type , bytes.Length)
- {
- Sha1Code = ShaHashHelper.GetSHA1(bytes),
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
- };
- return model;
- }
- public async Task<AzureBlobModel> UploadFile(IFormFile file, string fileSpace = "wordfiles", bool contentTypeDefault = true)
- {
- long bizno= IdWorker.getInstance().NextId();
- string groupName = fileSpace + "/" + DateTime.Now.ToString("yyyyMMdd")+"/"+ bizno;
- string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
- // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- StorageUri url = blobContainer.StorageUri;
- string[] names = file.FileName.Split(".");
- string name = "";
- for (int i = 0; i < names.Length - 1; i++)
- {
- name = name + names[i];
- }
- if (names.Length <= 1)
- {
- name = name + "_" + newFileName;
- }
- else
- {
- name = name + "_" + newFileName + "." + names[names.Length - 1];
- }
- var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
- var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
- var blockBlob = blobContainer.GetBlockBlobReference(name);
- string fileext = filename.Substring(filename.LastIndexOf(".") > 0 ? filename.LastIndexOf(".") : 0);
- if (!contentTypeDefault)
- {
- ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
- if (!string.IsNullOrEmpty(content_type))
- {
- blockBlob.Properties.ContentType = content_type;
- }
- }
- await blockBlob.UploadFromStreamAsync(file.OpenReadStream());
- string sha1 = ShaHashHelper.GetSHA1(file.OpenReadStream());
- AzureBlobModel model = new AzureBlobModel(file, _options.Container, groupName, name)
- {
- Sha1Code=sha1,
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + name
- };
- return model;
- }
- public AzureBlobModel UploadFileByFolderNAsyn(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
- {
- string groupName = fileSpace + "/" + folder;
- // string newFileName = sha1Code;
- // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- StorageUri url = blobContainer.StorageUri;
- string[] names = fileName.Split(".");
- // string name ;
- //for (int i = 0; i < names.Length - 1; i++)
- //{
- // name = name + names[i];
- //}
- //if (names.Length <= 1)
- //{
- // name = newFileName;
- //}
- //else
- //{
- // name = newFileName + "." + names[names.Length - 1];
- //}
- //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
- //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
- var blockBlob = blobContainer.GetBlockBlobReference(fileName);
- string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
- if (!contentTypeDefault)
- {
- ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
- if (!string.IsNullOrEmpty(content_type))
- {
- blockBlob.Properties.ContentType = content_type;
- }
- else
- {
- blockBlob.Properties.ContentType = "application/octet-stream";
- }
- }
- blockBlob.UploadFromStreamAsync(fileSteam).GetAwaiter().GetResult() ;
- AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
- {
- Sha1Code = ShaHashHelper.GetSHA1(fileSteam),
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
- };
- return model;
- }
- public async Task<AzureBlobModel> UploadFileByFolder(Stream fileSteam, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
- {
-
- string groupName = fileSpace + "/" + folder;
- // string newFileName = sha1Code;
- // await InitializeBlob(DateTime.Now.ToString("yyyyMMdd"));
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- StorageUri url = blobContainer.StorageUri;
- string[] names = fileName.Split(".");
- // string name ;
- //for (int i = 0; i < names.Length - 1; i++)
- //{
- // name = name + names[i];
- //}
- //if (names.Length <= 1)
- //{
- // name = newFileName;
- //}
- //else
- //{
- // name = newFileName + "." + names[names.Length - 1];
- //}
- //var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
- //var filename = Path.Combine(parsedContentDisposition.FileName.Trim('"'));
- var blockBlob = blobContainer.GetBlockBlobReference(fileName);
- string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
- if (!contentTypeDefault)
- {
- ContentTypeDict.dict.TryGetValue(fileext, out string content_type);
- if (!string.IsNullOrEmpty(content_type))
- {
- blockBlob.Properties.ContentType = content_type;
- }
- else {
- blockBlob.Properties.ContentType = "application/octet-stream";
- }
- }
- await blockBlob.UploadFromStreamAsync(fileSteam);
- string sha1 = ShaHashHelper.GetSHA1(fileSteam);
- AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, fileSteam.Length)
- {
- Sha1Code = sha1,
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
- };
- return model;
- }
- public async Task<AzureBlobModel> UploadTextByFolder(string text, string folder, string fileName, string fileSpace = "pptx", bool contentTypeDefault = true)
- {
- string groupName = fileSpace + "/" + folder;
- blobContainer = InitializeBlob(groupName); //blobClient.GetContainerReference(groupName);
- StorageUri url = blobContainer.StorageUri;
-
- var blockBlob = blobContainer.GetBlockBlobReference(fileName);
- string fileext = fileName.Substring(fileName.LastIndexOf(".") > 0 ? fileName.LastIndexOf(".") : 0);
- string content_type = "application/octet-stream";
- if (!contentTypeDefault)
- {
- ContentTypeDict.dict.TryGetValue(fileext, out string contenttype);
- if (!string.IsNullOrEmpty(contenttype))
- {
- blockBlob.Properties.ContentType = contenttype;
- content_type = contenttype;
- }
- else
- {
- blockBlob.Properties.ContentType = content_type;
- }
- }
- else
- {
- blockBlob.Properties.ContentType = content_type;
- }
-
- await blockBlob.UploadTextAsync(text);
- byte[] bytes = System.Text.Encoding.Default.GetBytes(text);
- AzureBlobModel model = new AzureBlobModel(fileName, _options.Container, groupName, fileName, folder, blockBlob.Properties.ContentType, bytes.Length)
- {
- Sha1Code = ShaHashHelper.GetSHA1(bytes),
- BlobUrl = url.PrimaryUri.ToString().Split("?")[0] + "/" + fileName
- };
- return model;
- }
- /// <summary>
- /// 在容器上创建共享访问策略。
- /// </summary>
- /// <param name="container">A reference to the container.</param>
- /// <param name="policyName">The name of the stored access policy.</param>
- public async Task<bool> CreateSharedAccessPolicyAsync(string policyName,
- string containerName = null)
- {
-
- blobContainer = await CreateContainer(_options.Container);
- //Create a new shared access policy and define its constraints.
- SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
- {
- SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
- Permissions = SharedAccessBlobPermissions.Delete
- };
- //Get the container's existing permissions.
- BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
- if (permissions.SharedAccessPolicies.Count < 5)
- {
- //Add the new policy to the container's permissions, and set the container's permissions.
- permissions.SharedAccessPolicies.TryAdd(policyName, sharedPolicy);
- await blobContainer.SetPermissionsAsync(permissions);
- return true;
- }
- else return false;
- }
- /// <summary>
- /// 删除容器上共享访问策略。
- /// </summary>
- /// <param name="container">A reference to the container.</param>
- /// <param name="policyName">The name of the stored access policy.</param>
- public async Task DeleteSharedAccessPolicyAsync(string policyName,
- string containerName = null)
- {
-
- blobContainer = await CreateContainer(_options.Container);
- BlobContainerPermissions permissions = await blobContainer.GetPermissionsAsync();
- permissions.SharedAccessPolicies.Remove(policyName);
- await blobContainer.SetPermissionsAsync(permissions);
-
- }
- /// <summary>
- ///为 blob 容器创建服务 SAS
- /// 若要为容器创建服务 SAS,请调用 CloudBlobContainer.GetSharedAccessSignature 方法。
- ///下面的代码示例在容器上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在容器上创建一个临时 SAS。
- /// </summary>
- /// <param name="container"></param>
- /// <param name="storedPolicyName"></param>
- /// <returns></returns>
- public async Task<(string, string, string)> GetContainerSasUri(string containerName = null, string storedPolicyName = null)
- {
- string sasContainerToken;
-
- blobContainer = await CreateContainer(_options.Container);
- // If no stored policy is specified, create a new access policy and define its constraints.
- if (storedPolicyName == null)
- {
- // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
- // to construct a shared access policy that is saved to the container's shared access policies.
- SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
- {
- // 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.
- // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
- SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
- SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
- Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create| SharedAccessBlobPermissions.Read
- };
- // Generate the shared access signature on the container, setting the constraints directly on the signature.
- sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
- }
- else
- {
- // Generate the shared access signature on the container. In this case, all of the constraints for the
- // shared access signature are specified on the stored access policy, which is provided by name.
- // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
- sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
- }
- // Return the URI string for the container, including the SAS token.
-
- return (blobContainer.Uri.Scheme+ "://"+ blobContainer.Uri.Host.ToString() , blobContainer.Name, sasContainerToken);
- }
- public async Task<(string, string)> GetContainerSasUriRead(string containerName, string storedPolicyName = null)
- {
- string sasContainerToken;
- blobContainer = await CreateContainer(containerName);
- // If no stored policy is specified, create a new access policy and define its constraints.
- if (storedPolicyName == null)
- {
- // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
- // to construct a shared access policy that is saved to the container's shared access policies.
- SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
- {
- // 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.
- // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
- SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
- SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
- Permissions = SharedAccessBlobPermissions.Read
- };
- // Generate the shared access signature on the container, setting the constraints directly on the signature.
- sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
- }
- else
- {
- // Generate the shared access signature on the container. In this case, all of the constraints for the
- // shared access signature are specified on the stored access policy, which is provided by name.
- // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
- sasContainerToken = blobContainer.GetSharedAccessSignature(null, storedPolicyName);
- }
- // Return the URI string for the container, including the SAS token.
- return (blobContainer.Uri.ToString(), sasContainerToken);
- }
- public async Task<KeyValuePair<string, object>> GetContainerSasUri(BlobSas blobSas, bool isRead)
- {
- CloudBlobContainer blobContainer;
- if (blobSas.role == "system")
- {
- blobContainer = await CreateContainer(_options.Container);
- }
- else
- {
- blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#", ""));
- }
- // If no stored policy is specified, create a new access policy and define its constraints.
- // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
- // to construct a shared access policy that is saved to the container's shared access policies.
- DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
- long time = dateTime.ToUnixTimeMilliseconds();
- SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
- {
- // 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.
- // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
- SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
- SharedAccessExpiryTime = dateTime,
- Permissions = SharedAccessBlobPermissions.Read
- };
- // Generate the shared access signature on the container, setting the constraints directly on the signature.
- string sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
- KeyValuePair<string, object> dict = new KeyValuePair<string, object>( blobContainer.Name, new { url = blobContainer.Uri, sas = sasContainerToken, timeout = time } );
- return dict;
- }
- public async Task<Dictionary<string,object>> GetBlobSasUri(BlobSas blobSas,bool isRead) {
- string sasBlobToken;
- CloudBlobContainer blobContainer;
- if (blobSas.role == "system")
- {
- blobContainer = await CreateContainer(_options.Container);
- }
- else {
- blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#",""));
- }
- // Create a new access policy and define its constraints.
- // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
- // to construct a shared access policy that is saved to the container's shared access policies.
- DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
- SharedAccessBlobPolicy adHocSAS = null;
- if (isRead)
- {
- adHocSAS = new SharedAccessBlobPolicy()
- {
- // 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.
- // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
- SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
- SharedAccessExpiryTime = dateTime,
- Permissions = SharedAccessBlobPermissions.Read
- };
- }
- else
- {
- adHocSAS = new SharedAccessBlobPolicy()
- {
- // 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.
- // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
- SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
- SharedAccessExpiryTime = dateTime,
- Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
- };
- }
- Dictionary<string, object> dict = new Dictionary<string, object>();
- long time = dateTime.ToUnixTimeMilliseconds();
- List<string> folders = BaseConfigModel.Configuration.GetSection("Azure:Blob:" + blobSas.role).Get<List<string>>();
- if (folders.IsNotEmpty())
- {
- foreach (string floder in folders) {
- string cates = floder;
- if (blobSas.role == "student") {
- if (string.IsNullOrEmpty(blobSas.code)) {
- throw new BizException("请设置学生编码!", ResponseCode.PARAMS_ERROR);
- }
- cates = floder.Replace("{studentId}", blobSas.code);
- }
- // Get a reference to a blob within the container.
- // Note that the blob may not exist yet, but a SAS can still be created for it.
- CloudBlockBlob blob = blobContainer.GetBlockBlobReference(cates);
- // Generate the shared access signature on the blob, setting the constraints directly on the signature.
- sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
- dict.Add(cates, new { url=blob.Uri,sas=sasBlobToken , timeout = time });
- }
- }
- return dict;
- }
-
- /// <summary>
- /// 若要为 blob 创建服务 SAS,请调用 CloudBlob.GetSharedAccessSignature 方法。
- ///下面的代码示例在 blob 上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在 Blob 上创建一个临时 SAS。
- /// </summary>
- /// <param name="container"></param>
- /// <param name="blobName"></param>
- /// <param name="policyName"></param>
- /// <returns></returns>
- public async Task<string> GetBlobSasUri(string blobName, string containerName=null, string policyName = null)
- {
- string sasBlobToken;
-
- blobContainer =await CreateContainer(_options.Container);
- // Get a reference to a blob within the container.
- // Note that the blob may not exist yet, but a SAS can still be created for it.
- CloudBlockBlob blob = blobContainer.GetBlockBlobReference( blobName );
- if (policyName == null)
- {
- // Create a new access policy and define its constraints.
- // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
- // to construct a shared access policy that is saved to the container's shared access policies.
- SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
- {
- // 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.
- // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
- SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
- SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
- Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
- };
- // Generate the shared access signature on the blob, setting the constraints directly on the signature.
- sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
- }
- else
- {
- // Generate the shared access signature on the blob. In this case, all of the constraints for the
- // shared access signature are specified on the container's stored access policy.
- sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
- }
- // Return the URI string for the container, including the SAS token.
- return blob.Uri + sasBlobToken;
- }
- public async Task<List<BlobFileDto>> GetBlobDirectory(string containerName, string blobName)
- {
- blobContainer = await CreateContainer(containerName);
- CloudBlobDirectory cloudBlobDirectory = blobContainer.GetDirectoryReference(blobName);
- List<BlobFileDto> blobProperties = new List<BlobFileDto>();
- blobProperties = GetBlobProperties(blobProperties, cloudBlobDirectory);
- return blobProperties;
- }
- public List<BlobFileDto> GetBlobProperties(List<BlobFileDto> blobProperties, CloudBlobDirectory blobDirectory)
- {
- IEnumerable<IListBlobItem> listBlobItems1 = blobDirectory.ListBlobsSegmentedAsync(new BlobContinuationToken()).GetAwaiter().GetResult().Results;
- foreach (IListBlobItem listBlobItem in listBlobItems1)
- {
- if (listBlobItem.GetType() == typeof(CloudBlobDirectory))
- {
- CloudBlobDirectory cloudBlobDirectory = (CloudBlobDirectory)listBlobItem;
- blobProperties = GetBlobProperties(blobProperties, cloudBlobDirectory);
- }
- else
- {
- CloudBlob blobaa = (CloudBlob)listBlobItem;
- blobaa.FetchAttributesAsync();
- BlobFileDto blobFileDto = new BlobFileDto
- {
- name = blobaa.Name,
- length = blobaa.Properties.Length,
- contentType = blobaa.Properties.ContentType,
- created = blobaa.Properties.Created != null ? blobaa.Properties.Created.Value.ToUnixTimeMilliseconds() : 0,//blobaa.Properties.Created.IsNull() ? 0 :
- lastModified = blobaa.Properties.LastModified != null ? blobaa.Properties.LastModified.Value.ToUnixTimeMilliseconds() : 0,//blobaa.Properties.LastModified.IsNull()? 0:
- url = blobaa.Uri.AbsoluteUri,
- BlobType = blobaa.BlobType.ToString()
- };
- blobProperties.Add(blobFileDto);
- }
- }
- return blobProperties;
- }
- public async Task<string> GetBlobSasUriRead(string containerName, string blobName, string policyName = null)
- {
- string sasBlobToken;
- blobContainer = await CreateContainer(containerName);
- CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);
- if (policyName == null)
- {
- SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
- {
- SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
- SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
- Permissions = SharedAccessBlobPermissions.Read
- };
- sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
- }
- else
- {
- sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
- }
- return blob.Uri + sasBlobToken;
- }
- private async Task<CloudBlobContainer> CreateContainer(string containerName)
- {
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_options.ConnectionString);
- CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
- CloudBlobContainer container = blobClient.GetContainerReference(containerName);
- await container.CreateIfNotExistsAsync();
- return container;
- }
- public async Task Deleteblob(string azureBlobSAS)
- {
-
- (string, string) a = BlobUrlString(azureBlobSAS);
- string ContainerName = a.Item1;
- string BlobName = a.Item2;
- string PolicyName = "DeletePolicy";
- try
- {
- bool flg = await CreateSharedAccessPolicyAsync(PolicyName);
- if (flg)
- {
- string SAS = await GetBlobSasUri(BlobName, null, PolicyName);
- CloudBlockBlob blob = new CloudBlockBlob(new Uri(SAS));
- await blob.DeleteAsync();
- }
- // await DeleteSharedAccessPolicyAsync(PolicyName);
- }
- catch (Exception e) {
- throw new BizException(e.StackTrace);
- }
- finally {
- await DeleteSharedAccessPolicyAsync(PolicyName);
- }
- }
- private static (string, string) BlobUrlString(string sasUrl)
- {
- sasUrl = sasUrl.Substring(8);
- string[] sasUrls = sasUrl.Split("/");
- string ContainerName;
- ContainerName = sasUrls[1].Clone().ToString();
- string item = sasUrls[0] + "/" + sasUrls[1] + "/";
- string blob = sasUrl.Replace(item, "");
- return (ContainerName, blob);
- }
- }
- }
|