栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

c# Sastoken方式访问微软blob帮助类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c# Sastoken方式访问微软blob帮助类

c# sastoken方式访问微软blob,生成sastoken,自定义有效期及访问权限

public class BlobHelperBySas
    {
        private static CloudStorageAccount storageAccount = null;
        private static string filesharebase = "";
        private static CloudBlobClient blobClient = null;
        static BlobHelperBySas()
        {
            var authSasToken = ConfigurationManager.AppSettings["blobsasconnectionstring"]; 
            var blobAccountName = ConfigurationManager.AppSettings["blobaccountname"];
            StorageCredentials accountSAS = new StorageCredentials(authSasToken);
            // Use these credentials and the account name to create a Blob service client.
            CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, blobAccountName, endpointSuffix: null, useHttps: true);
            blobClient = accountWithSAS.CreateCloudBlobClient();
            var url = blobClient.BaseUri.ToString();
            if (url.LastIndexOf("/").Equals(url.Length - 1))
            {
                url = url.Substring(0, url.Length - 1);
            }
            filesharebase = url;
        }
        /// 
        /// 上传本地文件到blobfileshare
        /// 
        /// 本地路径
        /// blob路径
        public static void UploadFileToBlob(string localPath, string toPath)
        {
            UploadFile(toPath, localPath: localPath);
        }
        /// 
        /// 上传文件流到blob
        /// 
        /// 
        /// 
        /// 
        public static void UploadStreamToBlob(Stream stream, int streamLength, string toPath)
        {
            UploadFile(toPath, 2, stream: stream, length: streamLength);
        }
        /// 
        /// 上传文件流到blob
        /// 
        /// 
        /// 
        /// 
        public static void UploadByteToBlob(byte[] by, int length, string toPath)
        {
            UploadFile(toPath, 3, by: by, length: length);
        }
        /// 
        /// 上传文件到blob 1物理路径上传 2文件流上传
        /// 
        /// 
        /// 
        /// 本地物理路径
        public static void UploadFile(string toPath, int uploadType = 1, string localPath = "", Stream stream = null, int length = 0, byte[] by = null)
        {
            var splitArrs = toPath.Split(new string[] { "/", "\" }, StringSplitOptions.RemoveEmptyEntries);
            CloudBlobContainer container = blobClient.GetContainerReference(splitArrs[0]);
            if (!container.Exists())
            {
                container.Create();
            }
            var splitLs = splitArrs.ToList();
            splitLs.RemoveAt(0);
            var blobpath = string.Join("/", splitLs.ToArray());
            CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(blobpath);
            if (uploadType == 1)
            {
                if (string.IsNullOrEmpty(localPath))
                {
                    throw new Exception("上传类型为本地文件上传时,物理路径不能为空");
                }
                cloudBlockBlob.UploadFromFileAsync(localPath);
            }
            else if (uploadType == 2)
            {
                if (stream == null || length == 0)
                {
                    throw new Exception("上传类型为流上传时,流和长度不能为空");
                }
                cloudBlockBlob.UploadFromStreamAsync(stream, length);
            }
            else if (uploadType == 3)
            {
                if (by == null)
                {
                    throw new Exception("二进制内容不能为空");
                }
                cloudBlockBlob.UploadFromByteArrayAsync(by, 0, length);
            }
        }
        /// 
        /// 删除blob的文件
        /// 
        /// blob路径
        public static void DeleteBlodFile(string blodPath)
        {
            var splitArrs = blodPath.Split(new string[] { "/", "\" }, StringSplitOptions.RemoveEmptyEntries);
            CloudBlobContainer container = blobClient.GetContainerReference(splitArrs[0]);
            if (!container.Exists())
            {
                return;
            }
            var splitLs = splitArrs.ToList();
            splitLs.RemoveAt(0);
            var blobpath = string.Join("/", splitLs.ToArray());
            CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(blobpath);
            if (cloudBlockBlob.Exists())
            {
                cloudBlockBlob.DeleteAsync();
            }
        }

        /// 
        /// 资源url地址
        /// 
        /// 
        /// 
        public static string GetResourceUrlWithSas(string blobFilePath, string sasToken = "")
        {
            if (string.IsNullOrEmpty(sasToken))
            {
                var splitArrs = blobFilePath.Split(new string[] { "/", "\" }, StringSplitOptions.RemoveEmptyEntries);
                sasToken = GetAccountSASToken(splitArrs[0]);
            }
            return filesharebase + blobFilePath + sasToken;
        }
        /// 
        /// 创建sastoken
        /// 
        /// 
        /// 
        public static string GetAccountSASToken(string containerName, int expireMonth = 3)
        {
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(expireMonth),
                Permissions = SharedAccessBlobPermissions.Read
            };
            // Return the SAS token.
            return container.GetSharedAccessSignature(adHocPolicy, null);
        }
        public static void TestContainer(string localPath)
        {
            var containerSas = "https://testresource.blob.core.chinacloudapi.cn/testdata?st=2018-08-15T03%3A34%3A45Z&se=2019-08-16T03%3A34%3A00Z&sp=rwdl&sv=2018-03-28&sr=c&sig=zNM0GUOdzuyZAoBV5wuUb28r5OmJPs%2BdStoNAHn4f2c%3D";
            CloudBlobContainer container = new CloudBlobContainer(new Uri(containerSas));
            CloudBlockBlob blob = container.GetBlockBlobReference("20180815/CN2245689/测试图片.jpg");
            blob.UploadFromFile(localPath);
        }
        public static void TestBlobSas()
        {
            var containerSas = "https://testresource.blob.core.chinacloudapi.cn/testdata?st=2018-08-15T03%3A34%3A45Z&se=2019-08-16T03%3A34%3A00Z&sp=rwdl&sv=2018-03-28&sr=c&sig=zNM0GUOdzuyZAoBV5wuUb28r5OmJPs%2BdStoNAHn4f2c%3D";
            CloudBlobContainer container = new CloudBlobContainer(new Uri(containerSas));
            CloudBlockBlob blob = container.GetBlockBlobReference("20180815/CN2245689/测试图片.jpg");
            SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(6),
                Permissions = SharedAccessBlobPermissions.Read
            };
            //var str = blob.Uri + blob.GetSharedAccessSignature(adHocPolicy);
            var str = blob.Uri + container.GetSharedAccessSignature(adHocPolicy);
        }
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1028469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号