【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (二)
问题描述
在上一篇博文(【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
【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (二)的更多相关文章
- 【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob
问题描述 在使用Azure的存储服务时候,如果上传的文件大于了100MB, 1GB的情况下,如何上传呢? 问题解答 使用Azure存储服务时,如果要上传文件到Azure Blob,有很多种工具可以实现 ...
- 【Azure 存储服务】代码版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享访问签名)
问题描述 在使用Azure存储服务,为了有效的保护Storage的Access Keys.可以使用另一种授权方式访问资源(Shared Access Signature: 共享访问签名), 它的好处可 ...
- 【Azure 存储服务】Java Azure Storage SDK V12使用Endpoint连接Blob Service遇见 The Azure Storage endpoint url is malformed
问题描述 使用Azure Storage Account的共享访问签名(Share Access Signature) 生成的终结点,连接时遇见 The Azure Storage endpoint ...
- 玩转Windows Azure存储服务——网盘
存储服务是除了计算服务之外最重要的云服务之一.说到云存储,大家可以想到很多产品,例如:AWS S3,Google Drive,百度云盘...而在Windows Azure中,存储服务却是在默默无闻的工 ...
- 解读 Windows Azure 存储服务的账单 – 带宽、事务数量,以及容量
经常有人询问我们,如何估算 Windows Azure 存储服务的成本,以便了解如何更好地构建一个经济有效的应用程序.本文我们将从带宽.事务数量,以及容量这三种存储成本的角度探讨这一问题. 在使用 W ...
- C# Socket服务端与客户端通信(包含大文件的断点传输)
步骤: 一.服务端的建立 1.服务端的项目建立以及页面布局 2.各功能按键的事件代码 1)传输类型说明以及全局变量 2)Socket通信服务端具体步骤: (1)建立一个Socket (2)接收 ...
- 使用kbmmw 的REST 服务实现上传大文件
我们在使用kbmmw的REST 服务时,经常会下载和上传大文件.例如100M以上的.kbmmw的rest服务中 提供标准的文件下载,上传功能,基本上就是打开文件,发送,接收,没有做特殊处理.这些对于文 ...
- webApi2 上传大文件代码
上传大文件,取消内存缓存: GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), ...
- PHP代码中使用post参数上传大文件
今天连续碰到了两个同事向我反应上传大文件(8M)失败的事情! 都是在PHP代码中通常使用post参数进行上传文件时,当文件的大小大于8M时,上传不能不成功. 首先,我想到了nginx的client_m ...
- 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例
什么是表存储 Azure 表存储是一项用于在云中存储结构化 NoSQL 数据的服务,通过无结构化的设计提供键/属性存储. 因为表存储无固定的数据结构要求,因此可以很容易地随着应用程序需求的发展使数据适 ...
随机推荐
- 关于Js debounce(防抖)函数和throttle(节流)小结
闭包的实际运用防抖 防抖:当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次, 如果设定的时间到来之前,又一次触发了事件,就重新开始 延时. (如果在一段时间内,又触发了该事件:就 ...
- vm-storage在全部都是旧metric情况下的写入性能测试
作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 接上篇:测试所有metric都是存在过的metric的情况 ...
- 【一文搞定】Linux、Mac、Windows安装Docker与配置教程!
目录 一.Windows 安装 1.1 安装与启用 Hyper-V 1.2 安装 WSL 1.3 Docker Desktop 官方下载 1.4 安装Docker Desktop 二.MacOS 安装 ...
- vim 从嫌弃到依赖(22)——自动补全
这篇文章我们将讨论 vim 自带的自动补全功能.当然,针对自动补全功能有许多好用的插件,但是了解vim自带的功能有助于我们更好的用来插件的补全功能.因为我见过有的配置文件将插件的功能配置的比原有的更难 ...
- Spring框架源码分析
目录 Spring核心思想 Spring源码编译 自定义实现Spring框架IOC与DI Spring源码Ioc核心模块分析 BeanDefinition整体介绍 FactoryBean接口的使用 B ...
- C/C++ 病毒破坏手法总结
针对注册表恶意修改: #include <stdio.h> #include <Windows.h> // 禁用系统任务管理器 void RegTaskmanagerForbi ...
- P2572 [SCOI2010] 序列操作 题解
题解:序列操作 比较综合的 ds 题,综合了线段树常见的几种操作:维护最大子段和.区间翻转.区间求和.区间覆盖 . 维护子段和常见的我们维护三类东西: 前缀最长连续段.后缀最长连续段.当前区间上的最大 ...
- 回顾复习之坐标DP
定义 坐标型动态规划一般是给定网格.序列,求满足条件的MAX或MIN. 开数组时,dp[i]一般代表以ai结尾的满足条件的子序列,dp[i][j]代表以i.j结尾的满足条件的最优解 例题 数塔 典中典 ...
- 从零开始的微信小程序入门教程(三),有趣且好玩的数据绑定
壹 ❀ 引 我在从零开始的微信小程序入门教程(二),初识WXML与WXSS一文中简单介绍了小程序组件与小程序样式相关概念,在了解这两者之后,其实我们已经可以搭建出简单的静态页面,与书写HTML页面一样 ...
- NC20812 绿魔法师
题目链接 题目 题目描述 "我不知道你在说什么,因为我只是个pupil."--绿魔法师 一个空的可重集合S. n次操作,每次操作给出x,k,p,执行以下操作: 1.在S中加入x. ...