【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 数据的服务,通过无结构化的设计提供键/属性存储. 因为表存储无固定的数据结构要求,因此可以很容易地随着应用程序需求的发展使数据适 ...
随机推荐
- Windows 2019 standard 安装 Sqlserver 2019 Standard 时报错 不知道如何处理
Microsoft Windows [版本 10.0.17763.1] (c) 2018 Microsoft Corporation.保留所有权利. D:\>setup.exe Microsof ...
- Oracle Linux7 与Oracle Linux8 下载rpm包的位置
Oracle Linux 7 http://yum.oracle.com/repo/OracleLinux/OL7/latest/x86_64/index.html 索引页 http://yum.or ...
- 京东哥伦布即时设计平台ChatGPT落地实践
一.平台介绍 即时设计平台是一个即时搭建c端楼层的开发平台,支持通过导入relay设计稿url完成Ui2Code,在此基础上完成前端可视化搭建,同时支持通过ChatGPT完成一句话需求,搭建后的楼层自 ...
- vue中$once的使用
$once 可以给组件实例绑定一个自定义事件,但该事件只能被触发一次,触发之后随即被移除 $once的简单使用 <template> <div> <button @cli ...
- js判断一个时间是否在某一个时间段内
很多时候,我们需要对时间进行处理: 比如说:获取当前的时间 判断某一个时间是否在一段时间内:如果在显示出某一个按钮: 让用户可以操作:如果不在,按钮隐藏 这个时候,我们就需要对时间进行处理了 < ...
- 百度指数 Cipher-Text、百度翻译 Acs-Token 逆向分析
K 哥之前写过一篇关于百度翻译逆向的文章,也在 bilibili 上出过相应的视频,最近在 K 哥爬虫交流群中有群友提出,百度翻译新增了一个请求头参数 Acs-Token,如果不携带该参数,直接按照以 ...
- 小白学k8s(5)k8s中的service
k8s中的service service存在的意义 Pod与Service的关系 Port port targetPort nodePort IP Node IP Pod IP Cluster IP ...
- python快速入门【六】----真题测试
python入门合集: python快速入门[一]-----基础语法 python快速入门[二]----常见的数据结构 python快速入门[三]-----For 循环.While 循环 python ...
- 8.4 ProcessHeap
ProcessHeap 是Windows进程的默认堆,每个进程都有一个默认的堆,用于在进程地址空间中分配内存空间.默认情况下ProcessHeap由内核进行初始化,该堆中存在一个未公开的属性,它被设置 ...
- MySQL 权限与备份管理(精简笔记)
MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RD ...