问题描述

在上一篇博文(【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 (二)的更多相关文章

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

    问题描述 在使用Azure的存储服务时候,如果上传的文件大于了100MB, 1GB的情况下,如何上传呢? 问题解答 使用Azure存储服务时,如果要上传文件到Azure Blob,有很多种工具可以实现 ...

  2. 【Azure 存储服务】代码版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享访问签名)

    问题描述 在使用Azure存储服务,为了有效的保护Storage的Access Keys.可以使用另一种授权方式访问资源(Shared Access Signature: 共享访问签名), 它的好处可 ...

  3. 【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 ...

  4. 玩转Windows Azure存储服务——网盘

    存储服务是除了计算服务之外最重要的云服务之一.说到云存储,大家可以想到很多产品,例如:AWS S3,Google Drive,百度云盘...而在Windows Azure中,存储服务却是在默默无闻的工 ...

  5. 解读 Windows Azure 存储服务的账单 – 带宽、事务数量,以及容量

    经常有人询问我们,如何估算 Windows Azure 存储服务的成本,以便了解如何更好地构建一个经济有效的应用程序.本文我们将从带宽.事务数量,以及容量这三种存储成本的角度探讨这一问题. 在使用 W ...

  6. C# Socket服务端与客户端通信(包含大文件的断点传输)

    步骤: 一.服务端的建立 1.服务端的项目建立以及页面布局 2.各功能按键的事件代码 1)传输类型说明以及全局变量 2)Socket通信服务端具体步骤:   (1)建立一个Socket   (2)接收 ...

  7. 使用kbmmw 的REST 服务实现上传大文件

    我们在使用kbmmw的REST 服务时,经常会下载和上传大文件.例如100M以上的.kbmmw的rest服务中 提供标准的文件下载,上传功能,基本上就是打开文件,发送,接收,没有做特殊处理.这些对于文 ...

  8. webApi2 上传大文件代码

    上传大文件,取消内存缓存: GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), ...

  9. PHP代码中使用post参数上传大文件

    今天连续碰到了两个同事向我反应上传大文件(8M)失败的事情! 都是在PHP代码中通常使用post参数进行上传文件时,当文件的大小大于8M时,上传不能不成功. 首先,我想到了nginx的client_m ...

  10. 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例

    什么是表存储 Azure 表存储是一项用于在云中存储结构化 NoSQL 数据的服务,通过无结构化的设计提供键/属性存储. 因为表存储无固定的数据结构要求,因此可以很容易地随着应用程序需求的发展使数据适 ...

随机推荐

  1. 如何写RN样式 如何写RN组件 如何满屏 如何使用变量

    app.js 文本水平居中了哈 控制文本的大小 字体颜色等 只有在文本元素上去控制哈 import React from 'react'; import {View, Text, StyleSheet ...

  2. win10家庭版禁用更新

    前言 2020年初因为疫情在家远程办公,而我老家没有电脑,先后向两位大学生借了两台电脑来办公,发现一个现象:他们的电脑系统都是家庭版,也就是刚买电脑时安装的win10家庭版.也问了其它几位计算机专业的 ...

  3. 通过Demo学WPF—数据绑定(一)✨

    前言 想学习WPF,但是看视频教程觉得太耗时间,直接看文档又觉得似懂非懂,因此想通过看Demo代码+文档的方式进行学习. 准备 微软官方其实提供了WPF的一些Demo,地址为:microsoft/WP ...

  4. 大语言模型的预训练[5]:语境学习、上下文学习In-Context Learning:精调LLM、Prompt设计和打分函数设计以及ICL底层机制等原理详解

    大语言模型的预训练[5]:语境学习.上下文学习In-Context Learning:精调LLM.Prompt设计和打分函数(Scoring Function)设计以及ICL底层机制等原理详解 1.I ...

  5. 4.5 MinHook 挂钩技术

    MinHook是一个轻量级的Hooking库,可以在运行时劫持函数调用.它支持钩子API函数和普通函数,并且可以运行在32位和64位Windows操作系统上.其特点包括易于使用.高性能和低内存占用.M ...

  6. 关闭表单验证/关闭控制台async-validator警告

    找到util.js node_modules -> async-validator -> es -> util.js 将console.warn(type, errors)注释 如果 ...

  7. PHP中的正则表达式相关函数

    PHP中的正则表达式相关函数 常用的正则函数 1.执行一个正则表达式匹配 int preg_match ( string pattern , string subject [, array & ...

  8. 双端队列(deque)--python

    Python中的双端队列(deque)是一种特殊的数据结构,它允许在队列的两端进行插入和删除操作12.双端队列可以看成栈和队列的结合3.在Python中,我们可以使用collections模块中的de ...

  9. NSSRound16

    NSSRound16 RCE但是没有完全RCE 审题 审核代码,简单的md5绕过. 知识点 md5绕过,命令组合,shell里``中的内容会被当成代码执行 知识详解 md5等于的绕过方法 数组绕过 a ...

  10. 零基础入门学习Java之多线程

    多线程 话不多说,看代码 1.什么是多线程 众所周知CPU单线程的东西,也就是说在同一时间内程序只能去做一件事情,但很多时候比如说多人买票.龟兔赛跑.游戏开发等都需要在同一时间内完成多个东西,因此就有 ...