首页 > 其他分享 >【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (二)

【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (二)

时间:2023-01-20 15:55:35浏览次数:61  
标签:Console 传大 示例 Storage WriteLine Azure 上传 Microsoft

问题描述

在上一篇博文(【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (一):https://www.cnblogs.com/lulight/p/17061631.html)中,介绍了第一种分片的方式上传文件。 本文章接着介绍第二种方式,使用 Microsoft.Azure.Storage.DataMovement 库中的 TransferManager.UploadAsync 通过并发的方式来上传大文件。

问题回答

第一步:添加 Microsoft.Azure.Storage.DataMovement  

dotnet add package Microsoft.Azure.Storage.DataMovement

第二步:编写示例代码

        String storageConnectionString = "xxxxxxxxxxxxxxxxxxx";

        CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
        CloudBlobClient blobclient = account.CreateCloudBlobClient();
        CloudBlobContainer blobcontainer = blobclient.GetContainerReference("uploadfiles-123");
        await blobcontainer.CreateIfNotExistsAsync();

        // 获取文件路径
        string sourcePath = @"C:\home\bigfiles0120.zip";
        CloudBlockBlob docBlob = blobcontainer.GetBlockBlobReference("bigfiles-2");
        await docBlob.DeleteIfExistsAsync();

        // 设置并发操作的数量
        TransferManager.Configurations.ParallelOperations = 64;
        // 设置单块 blob 的大小,它必须在 4MB 到 100MB 之间,并且是 4MB 的倍数,默认情况下是 4MB
        TransferManager.Configurations.BlockSize = 64 * 1024 * 1024;
        // 设置传输上下文并跟踪上传进度
        var context = new SingleTransferContext();
        UploadOptions uploadOptions = new UploadOptions
        {
            DestinationAccessCondition = AccessCondition.GenerateIfExistsCondition()
        };
        context.ProgressHandler = new Progress<TransferStatus>(progress =>
        {
            //显示上传进度
            Console.WriteLine("Bytes uploaded: {0}", progress.BytesTransferred);
        });
        // 使用 Stopwatch 查看上传所需时间
        var timer = System.Diagnostics.Stopwatch.StartNew();
        // 上传 Blob
        TransferManager.UploadAsync(sourcePath, docBlob, uploadOptions, context, CancellationToken.None).Wait();
        timer.Stop();
        Console.WriteLine("Time (millisecond):" + timer.ElapsedMilliseconds);
        Console.WriteLine("upload success");

第一种分片方式上传和第二步并发上传的代码执行对比:

 

全部代码

Program.cs

// See https://aka.ms/new-console-template for more information

Console.WriteLine("Hello, World! Start to upload big files...");

//第一种上传文件方法: Microsoft.WindowsAzure.Storage
Console.WriteLine("第一种上传文件方法: Microsoft.WindowsAzure.Storage");
await UploadMethodOne.WindowsAzureStorageUpload();

//第二种上传文件方法: Microsoft.Azure.Storage.DataMovement
Console.WriteLine("第二种上传文件方法: Microsoft.Azure.Storage.DataMovement");
await UploadMethodTwo.DataMovementUploadFiletoBlob();

Console.WriteLine("End!");

UploadMethodOne.cs

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

public static class UploadMethodOne
{
    public static async Task WindowsAzureStorageUpload()
    {
        TimeSpan backOffPeriod = TimeSpan.FromSeconds(2);
        int retryCount = 1;
        //设置请求选项
        BlobRequestOptions requestoptions = new BlobRequestOptions()
        {
            SingleBlobUploadThresholdInBytes = 1024 * 1024 * 10, //10MB
            ParallelOperationThreadCount = 12,
            RetryPolicy = new ExponentialRetry(backOffPeriod, retryCount),
        };

        //String storageConnectionString = System.Environment.GetEnvironmentVariable("StorageConnectionString", EnvironmentVariableTarget.User);
        //Console.WriteLine("String account string : "+storageConnectionString);
        String storageConnectionString = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
        CloudBlobClient blobclient = account.CreateCloudBlobClient();
        //设置客户端默认请求选项
        blobclient.DefaultRequestOptions = requestoptions;
        CloudBlobContainer blobcontainer = blobclient.GetContainerReference("uploadfiles-123");


        await blobcontainer.CreateIfNotExistsAsync();
        //文件路径,文件大小 
        string sourcePath = @"C:\home\bigfiles0120.zip";
        CloudBlockBlob blockblob = blobcontainer.GetBlockBlobReference("bigfiles-1");
        //设置单个块 Blob 的大小(分块方式)
        blockblob.StreamWriteSizeInBytes = 1024 * 1024 * 5;
        try
        {
            Console.WriteLine("uploading");
            //使用 Stopwatch 查看上传时间
            var timer = System.Diagnostics.Stopwatch.StartNew();
            using (var filestream = System.IO.File.OpenRead(sourcePath))
            {
                await blockblob.UploadFromStreamAsync(filestream);
            }
            timer.Stop();

            Console.WriteLine(timer.ElapsedMilliseconds);

            Console.WriteLine("Upload Successful, Time:" + timer.ElapsedMilliseconds);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }
}

 

UploadMethodTwo.cs

using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.DataMovement;
public static class UploadMethodTwo
{
    public async static Task DataMovementUploadFiletoBlob()
    {
        String storageConnectionString = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

        CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
        CloudBlobClient blobclient = account.CreateCloudBlobClient();
        CloudBlobContainer blobcontainer = blobclient.GetContainerReference("uploadfiles-123");
        await blobcontainer.CreateIfNotExistsAsync();

        // 获取文件路径
        string sourcePath = @"C:\home\bigfiles0120.zip";
        CloudBlockBlob docBlob = blobcontainer.GetBlockBlobReference("bigfiles-2");
        await docBlob.DeleteIfExistsAsync();

        // 设置并发操作的数量
        TransferManager.Configurations.ParallelOperations = 64;
        // 设置单块 blob 的大小,它必须在 4MB 到 100MB 之间,并且是 4MB 的倍数,默认情况下是 4MB
        TransferManager.Configurations.BlockSize = 64 * 1024 * 1024;
        // 设置传输上下文并跟踪上传进度
        var context = new SingleTransferContext();
        UploadOptions uploadOptions = new UploadOptions
        {
            DestinationAccessCondition = AccessCondition.GenerateIfExistsCondition()
        };
        context.ProgressHandler = new Progress<TransferStatus>(progress =>
        {
            //显示上传进度
            Console.WriteLine("Bytes uploaded: {0}", progress.BytesTransferred);
        });
        // 使用 Stopwatch 查看上传所需时间
        var timer = System.Diagnostics.Stopwatch.StartNew();
        // 上传 Blob
        TransferManager.UploadAsync(sourcePath, docBlob, uploadOptions, context, CancellationToken.None).Wait();
        timer.Stop();
        Console.WriteLine("Time (millisecond):" + timer.ElapsedMilliseconds);
        Console.WriteLine("upload success");
    }
}

 

参考资料

上传大文件到 Azure 存储块 Blob:https://docs.azure.cn/zh-cn/articles/azure-operations-guide/storage/aog-storage-blob-howto-upload-big-file-to-storage

 

标签:Console,传大,示例,Storage,WriteLine,Azure,上传,Microsoft
From: https://www.cnblogs.com/lulight/p/17062819.html

相关文章

  • Vue3中的异步组件defineAsyncComponentAPI的用法示例
    介绍当我们的项目达到一定的规模时,对于某些组件来说,我们并不希望一开始全部加载,而是需要的时候进行加载;这样的做得目的可以很好的提高用户体验。为了实现这个功能,Vue3中......
  • Spring Security XML示例
    SpringSecurityXML示例在本教程中,我们将使用SpringMVC 框架实现 SpringSecurity。所有示例都是SpringMVC,并且是使用Maven项目创建的。我们使用的是 SpringSecur......
  • 【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob
    问题描述在使用Azure的存储服务时候,如果上传的文件大于了100MB,1GB的情况下,如何上传呢?问题解答使用Azure存储服务时,如果要上传文件到AzureBlob,有很多种工具可以实现。如:Azu......
  • 【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob
    问题描述在使用Azure的存储服务时候,如果上传的文件大于了100MB,1GB的情况下,如何上传呢? 问题解答使用Azure存储服务时,如果要上传文件到AzureBlob,有很多种工具可以实现......
  • Spring远程处理(通过Hessian示例)
    借助于 HessianServiceExporter 和 HessianProxyFactoryBean 类,我们可以实现hessian提供的远程服务。Hessian的优势Hessian在整个防火墙上都能很好地工作。Hessian......
  • Spring远程处理(通过Burlap示例)
    Houssian和Burlap均由Coucho提供。借助于 BurlapServiceExporter 和 BurlapProxyFactoryBean 类,我们可以实现burlap提供的远程服务。Burlap的示例与Burlap相同,您只需......
  • Spring通过HTTP调用程序进行远程处理示例
    基于Web的客户端在上面给出的示例中,我们使用了基于控制台的客户端。我们也可以使用基于Web的客户端。您需要创建3个其他文件。在这里,我们使用以下文件:ClientInvoker.jav......
  • Spring MVC Tiles示例
    Spring提供了与apachetile框架的集成支持。因此,我们可以借助SpringTile支持简单地管理SpringMVC应用程序的布局。SpringMVC支持Tiles的优势SpringMVCTiles示例1、......
  • 性能测试指标推算及压测示例
    性能测试指标推算及压测示例根据提测范围、业务需求推算性能需求和指标(如事务数、并发数等),然后写脚本时可根据此模拟线程数和约束条件,最后执行压测、监控服务器资源、分析......
  • Spring MVC文件上传示例
    SpringMVC提供了一种上传文件的简便方法,它可以是图像或其他文件。让我们看一个使用SpringMVC上传文件的简单示例。必需的Jar文件要运行此示例,您需要加载:SpringCore......