Azure Blob Storage学习笔记——图片的上传,浏览,下载,删除

时间:2024-04-08 18:24:25

 1.通过NuGet将Azure Storage的相关包引入项目

Azure Blob Storage学习笔记——图片的上传,浏览,下载,删除

2.在config文件中写入相关帐号

    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
      <!--存储账号名称-->
      <add key="AccountName" value="account-name" />
      <!--存储账号**-->
      <add key="AccountKey" value="account-key" />
      <!--ContainerName,必须是小写-->
      <add key="ContainerName" value="images" />
      <!-- SAS过期时间xx秒-->
      <add key="expireseconds" value="60" />
      <add key="RecyclebinContainerName" value="recyclebin" />

3.Azure的相关操作

#region Azure Helper
        public static void EnsureContaierExists()
        {
            string containername = ConfigurationManager.AppSettings["ContainerName"].ToString();
            var container = GetContainer(containername);
            // 检查container是否被创建,如果没有,创建container
            container.CreateIfNotExists();
            var permissions = container.GetPermissions();
            //对Storage的访问权限是可以浏览Container
            permissions.PublicAccess = BlobContainerPublicAccessType.Off;
            container.SetPermissions(permissions);
        }

        public static CloudBlobContainer GetContainer(string containername)
        {
            //Get config from Web.Config
            string accountname = ConfigurationManager.AppSettings["AccountName"].ToString();
            string accountkey = ConfigurationManager.AppSettings["AccountKey"].ToString();
            string connectionString = GenerateConnectionString(accountname, accountkey);
            //Get Azure Storage Connection String 
            var account = CloudStorageAccount.Parse(connectionString);
            var client = account.CreateCloudBlobClient();
            //Get BlobContainer Object
            return client.GetContainerReference(containername);
        }

        public static string GenerateConnectionString(string accountname, string accountkey)
        {
            StringBuilder sbuilder = new StringBuilder();
            sbuilder.Append(@"BlobEndpoint=https://");
            sbuilder.Append(accountname);
            sbuilder.Append(".blob.core.windows.net/");

            sbuilder.Append(@";QueueEndpoint=https://");
            sbuilder.Append(accountname);
            sbuilder.Append(".queue.core.windows.net/");

            sbuilder.Append(@";TableEndpoint=https://");
            sbuilder.Append(accountname);
            sbuilder.Append(".table.core.windows.net/");

            sbuilder.Append(";AccountName=");
            sbuilder.Append(accountname);

            sbuilder.Append(";AccountKey=");
            sbuilder.Append(accountkey);

            return sbuilder.ToString();
        }
        public static string GetSAS(CloudBlockBlob blob)
        {
            string seconds = ConfigurationManager.AppSettings["expireseconds"].ToString();
            float result = 20;

            var sas = blob.GetSharedAccessSignature(
                new SharedAccessBlobPolicy()
                {
                    Permissions = SharedAccessBlobPermissions.Read,
                    SharedAccessExpiryTime = DateTime.UtcNow.AddSeconds(float.TryParse(seconds, out result) ? result : 0f)
                });
            var secureURl = blob.Uri.AbsoluteUri + sas;

            return secureURl.ToString();
        }
        #endregion

 

4.上传图片

    string sFileEXT = Path.GetExtension(imageName);
    string sFileMimeType = Utils.GetFileContentType(sFileEXT);
    Guid gID = Guid.NewGuid();
byte[] imageCONTENT = File.ReadAllBytes(imageName);   
string containername = ConfigurationManager.AppSettings["ContainerName"].ToString(); CloudBlockBlob blob = GetContainer(containername).GetBlockBlobReference(Sql.ToString(gID) + sFileEXT); blob.Properties.ContentType = sFileMimeType; using (MemoryStream ms = new MemoryStream(imageCONTENT, false)) { blob.UploadFromStream(ms); }
spImages_Update(ref gID,...);
//将图片的相关信息存入数据库

5.浏览图片(通过图片ID查看图片)

string filename =Sql.ToString(gID)+ sFileEXT; 
string containername = ConfigurationManager.AppSettings["ContainerName"].ToString();
CloudBlockBlob blob = APSqlProcs.GetContainer(containername).GetBlockBlobReference(filename);
string sSASURL = APSqlProcs.GetSAS(blob);
sSrc
= sSASURL;
//将Src传给前台的图片控件

6.下载图片

Response.ContentType = Sql.ToString(rdr["FILE_MIME_TYPE"]);
 sFileName = Path.GetFileName(Sql.ToString(rdr["FILENAME"]));
 Response.AddHeader("Content-Disposition", "attachment;filename=" + sFileName);
 string sFileEXT = Path.GetExtension(sFileName);
 string filename = gID.ToString() + sFileEXT;
 string containername = ConfigurationManager.AppSettings["ContainerName"].ToString();
 CloudBlockBlob blob = APSqlProcs.GetContainer(containername).GetBlockBlobReference(filename);
 using (MemoryStream memoryStream = new MemoryStream())
 {
      blob.DownloadToStream(memoryStream);
      byte[] bytes = new byte[memoryStream.Length];
    memoryStream.Seek(0, SeekOrigin.Begin);//memoryStream的指针在读入数据后指向了末尾,所以要重置到开始的位置,用memoryStream.Position = 0也可以
memoryStream.Read(bytes, 0, bytes.Length);
using (BinaryWriter bw = new BinaryWriter(Response.OutputStream))
{
bw.Write(bytes);
}
}

 7.删除图片(其实是将图片移动到名为recyclebin的Container里去,方便找回,可以写一个计划任务,定期删除recyclebin里的文件)

      private void DelImage(Guid gImageID, string sImageName)
        {
            string sFileEXT = Path.GetExtension(sImageName);
            string sFileMimeType = Utils.GetFileContentType(sFileEXT);
            string filename = gImageID.ToString() + sFileEXT;
            string sourceContainer = ConfigurationManager.AppSettings["ContainerName"].ToString();
            string targetContainer = ConfigurationManager.AppSettings["RecyclebinContainerName"].ToString();
            CloudBlockBlob sourceBlob = APSqlProcs.GetContainer(sourceContainer).GetBlockBlobReference(filename);
            CloudBlockBlob targetBlob = APSqlProcs.GetContainer(targetContainer).GetBlockBlobReference(filename);
            targetBlob.StartCopyAsync(sourceBlob);
            sourceBlob.Delete();
        }

 

注:相关操作请参考Microsoft Azure官方文章Get started with Azure Blob storage using .NET(https://docs.microsoft.com/en-us/azure/storage/storage-dotnet-how-to-use-blobs)