码迷,mamicode.com
首页 > Web开发 > 详细

.NET 使用 Azure Blob 存储图片或文件

时间:2017-07-13 16:04:00      阅读:832      评论:0      收藏:0      [点我收藏+]

标签:explore   解决   task   pen   ora   add   添加   review   get   

使用的是VS2017

一、先使用 NuGet 获取这两个包。 执行以下步骤:

在“解决方案资源管理器”中,右键单击你的项目并选择“管理 NuGet 包”。

1.在线搜索“WindowsAzure.Storage”,然后单击“安装” 以安装存储客户端库和依赖项。

2.在线搜索“WindowsAzure.ConfigurationManager”,然后单击“安装”以安装 Azure Configuration Manager。

会生成5个dll,如下图:

技术分享

封装代码如下:

需要先引用

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

1).AzureBlob.cs

技术分享
public class AzureBlob
{
    #region 私有变量
    //类的成员,用于创建Blob服务客户端
    CloudBlobClient blobClient;

    //容器和Blob其实就相当于文件夹、文件名

    /// <summary>
    /// 连接字符串
    /// </summary>
    private string storageConnectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
    #endregion

    #region 构造函数创建Blob服务客户端
    public AzureBlob()
    {
        //解析配置中的连接字符串
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
        //创建Blob服务客户端
        blobClient = storageAccount.CreateCloudBlobClient();
    }
    #endregion

    #region 获取块Blob引用
    /// <summary>
    /// 获取块Blob引用
    /// </summary>
    /// <param name="mycontainer">容器名</param>
    /// <param name="fileName">文件名</param>
    /// <returns></returns>
    public CloudBlockBlob GetContainer(string mycontainer, string fileName)
    {
        //获取容器的引用
        CloudBlobContainer container = blobClient.GetContainerReference(mycontainer);
        //获取块 Blob 引用
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        return blob;
    }
    #endregion

    #region 二进制形式上传文件
    /// <summary>
    /// 二进制形式上传文件
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="mycontainer">容器名</param>
    /// <param name="bytes">二进制形式的文件</param>
    /// <returns>异步信息</returns>
    public Task UploadToBlob(string fileName,string mycontainer,byte[] bytes)
    {
        //获取容器的引用
        CloudBlobContainer container = blobClient.GetContainerReference(mycontainer);
        //创建一个容器(如果该容器不存在)
        container.CreateIfNotExists();
        //设置该容器为公共容器,也就是说网络上能访问容器中的文件,但不能修改、删除
        container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
        //将Blob(文件)上载到容器中,如果已存在同名Blob,则覆盖它
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);//获取块 Blob 引用
        Task result = blockBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length);//将二进制文件上传
        return result;
    }
    #endregion

    #region 文件路径上传
    /// <summary>
    /// 文件路径上传
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="mycontainer">容器名</param>
    /// <param name="filePath">文件路径</param>
    /// <returns></returns>
    public string UploadToBlob(string fileName, string mycontainer,string filePath)
    {
        ////获取容器的引用
        CloudBlobContainer container = blobClient.GetContainerReference(mycontainer);
        //创建一个容器(如果该容器不存在)
        container.CreateIfNotExists();
        //设置该容器为公共容器,也就是说网络上能访问容器中的文件,但不能修改、删除
        container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
        //将Blob(文件)上载到容器中,如果已存在同名Blob,则覆盖它
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);//获取块 Blob 引用
        //文件路径
        using (var fileStream = System.IO.File.OpenRead(filePath))
        {
            blockBlob.UploadFromStream(fileStream);
        }
        return blockBlob.Uri.ToString();
    }
    #endregion

    #region 根据文件名和容器名取到Blob地址
    /// <summary>
    /// 根据文件名和容器名取到Blob地址
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="mycontainer">容器名</param>
    /// <returns></returns>
    public string GetBlobURI(string fileName, string mycontainer)
    {
        CloudBlockBlob blob = GetContainer(mycontainer, fileName);
        return blob.Uri.ToString();
    }
    #endregion

    #region 下载Blob
    /// <summary>
    /// 下载Blob
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="mycontainer">容器名</param>
    /// <param name="fliePath">文件路径</param>
    public void DownloadToFile(string fileName, string mycontainer, string fliePath)
    {
        CloudBlockBlob blob = GetContainer(mycontainer, fileName);
        using (var fileStream = File.OpenWrite(fliePath))
        {
            blob.DownloadToStream(fileStream); //将blob保存在指定路径
        }
    }
    #endregion

    #region 下载Blob
    /// <summary>
    /// 下载Blob
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="mycontainer">容器名</param>
    /// <param name="fliePath">文件路径</param>
    public string DownloadToStream(string fileName, string mycontainer)
    {
        CloudBlockBlob blob = GetContainer(mycontainer, fileName);
        string text;
        using (var memoryStream = new MemoryStream())
        {
            blob.DownloadToStream(memoryStream);
            text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
        }
        return text;
    }
    #endregion

    #region 下载Blob
    /// <summary>
    /// 下载Blob
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="mycontainer">容器名</param>
    /// <param name="fliePath">文件路径</param>
    public void DownloadToFileStream(string fileName, string mycontainer, string fliePath)
    {
        CloudBlockBlob blob = GetContainer(mycontainer, fileName);
        using (var fileStream = new FileStream(fliePath, FileMode.OpenOrCreate))
        {
            blob.DownloadToStream(fileStream); //将blob保存在指定路径
        };
    }
    #endregion

    #region 删除Blob
    /// <summary>
    /// 删除Blob
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="mycontainer">容器名</param>
    public void DeleteBlob(string fileName, string mycontainer)
    {
        CloudBlockBlob blob = GetContainer(mycontainer, fileName);
        blob.Delete();
    }
    #endregion
}
View Code

2).单元测试类:class AzureBlob_Test.cs

技术分享
[TestClass]
public class AzureBlob_Test
{
    AzureBlob azureBlob = new AzureBlob();
    private string containername = ConfigurationManager.AppSettings["userimg"].ToString();

    [TestMethod]
    public void TestUploadToBlob()
    {
        //string imgCode = ""

        //Byte[] buffer = Convert.FromBase64String(imgCode.Replace(" ", "+"));
        //var result = azureBlob.UploadToBlob("test", containername, buffer);

        string str = "userImg/430223198701159158_601421613.png";
        var str1 = str.Contains("/");

        Assert.IsTrue(str1);
    }

    [TestMethod] //OK
    public void TestGetBlobURI() 
    {
        var result = azureBlob.GetBlobURI("test", containername);
        Assert.IsNotNull(result);//https://08afc0c4store.blob.core.chinacloudapi.cn/images/test
    }

    [TestMethod] //OK
    public void TestUploadToBlob2()
    {
        var fileName = "1_2.jpg";
        var filePath = @"F:\img\"+ fileName;
        azureBlob.UploadToBlob(fileName, containername, filePath);
    }

    [TestMethod]
    public void TestDownloadToFile()
    {
        var fileName = "2017.jpg";
        var filePath = @"images\2017.jpg";
        //filePath = azureBlob.GetBlobURI(fileName, containername);
        azureBlob.DownloadToFile(fileName, containername, filePath);
    }

    [TestMethod]
    public void TestDownloadToStream()
    {
        var fileName = "2017.jpg";;
        //filePath = azureBlob.GetBlobURI(fileName, containername);
        azureBlob.DownloadToStream(fileName, containername);
    }

    [TestMethod]
    public void TestDownloadToFileStream()
    {
        var fileName = "2017.jpg"; ;
        var filePath = @"test\2017.jpg";
        //filePath = azureBlob.GetBlobURI(fileName, containername);
        azureBlob.DownloadToFileStream(fileName, containername, filePath);
    }

    [TestMethod] //OK
    public void TestDeleteBlob()
    {
        var fileName = "2017.jpg";
        azureBlob.DeleteBlob(fileName, containername);
    }
}
View Code

3).在web.config 下的<configuration>-><appSettings>下添加:

<!--存储图片连接字符串 -->
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=test;AccountKey=1234;EndpointSuffix=core.chinacloudapi.cn" />
<!--容器名,必须是小写-->
<add key="test" value="test" />

4).通过Azure Storage Explorer 6查看上传的图片,下载地址为:http://azurestorageexplorer.codeplex.com/releases/view/125870 下的 AzureStorageExplorer6Preview3.zip

 

参考:http://www.jianshu.com/p/bf265c6ceedd

          https://docs.azure.cn/zh-cn/storage/storage-dotnet-how-to-use-blobs 

相关开发资源 https://docs.azure.cn/zh-cn/storage/           

 

.NET 使用 Azure Blob 存储图片或文件

标签:explore   解决   task   pen   ora   add   添加   review   get   

原文地址:http://www.cnblogs.com/allenhua/p/7160068.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!