You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC如何结合Azure Blob Storage实现大文件分块上传?

ASP.NET MVC 实现Azure Blob Storage大文件分块上传(基于BlobClient)

核心说明

你当前使用的是Azure.Storage.Blobs新SDK(对应BlobClient),而CloudBlockBlob属于旧版WindowsAzure.Storage SDK,两者不兼容。直接基于新SDK的BlockBlobClient即可实现分块上传,无需切换旧库。

实现步骤与代码

以下是适配你现有代码的分块上传实现,以1MB块大小为例:

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

public async Task<string> UploadLargeFilesInChunks(string connectionString, IEnumerable<FileUploadModel> files, string blobContainer)
{
    const int chunkSize = 1024 * 1024; // 1MB 块大小
    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(blobContainer);

    foreach (var file in files)
    {
        // 获取块Blob客户端,确保创建的是块Blob类型
        BlockBlobClient blockBlobClient = containerClient.GetBlockBlobClient(file.FileName);
        await blockBlobClient.CreateIfNotExistsAsync(BlobType.Block);

        List<string> blockIds = new List<string>();
        using (Stream stream = file.InputStream)
        {
            byte[] buffer = new byte[chunkSize];
            int bytesRead;
            int blockIndex = 0;

            while ((bytesRead = await stream.ReadAsync(buffer, 0, chunkSize)) > 0)
            {
                // 生成唯一的块ID,需要Base64编码
                string blockId = Convert.ToBase64String(BitConverter.GetBytes(blockIndex));
                blockIds.Add(blockId);

                // 上传当前块
                using (MemoryStream chunkStream = new MemoryStream(buffer, 0, bytesRead))
                {
                    await blockBlobClient.StageBlockAsync(blockId, chunkStream);
                }

                blockIndex++;
            }
        }

        // 提交所有块,合并成完整Blob
        await blockBlobClient.CommitBlockListAsync(blockIds);
    }

    return "Success";
}

// 假设你的FileUploadModel定义如下(可根据实际调整)
public class FileUploadModel
{
    public string FileName { get; set; }
    public Stream InputStream { get; set; }
    // 其他属性如文件大小等可按需添加
}

关键细节说明

  • 块ID要求:每个块的ID必须是Base64编码的字符串,且同一Blob内的块ID唯一。这里用块索引转Base64确保唯一性。
  • 块大小限制:单个块最大支持100MB(最后一块大小可小于该值),你测试用1MB完全符合要求,后续扩展到1GB以上文件时无需调整块大小(只需循环处理更多块)。
  • 异常处理:可根据需求在上传块或提交块列表时添加异常捕获,比如记录失败的块ID,实现断点续传(需调用GetBlockListAsync查询已上传的块)。
  • Blob类型:必须确保创建的是BlockBlob类型,CreateIfNotExistsAsync(BlobType.Block)会自动处理。

测试建议

  1. 先用5MB文件测试,验证分块(5个1MB块)上传后合并的文件完整性。
  2. 后续测试大文件时,可添加进度跟踪(比如记录已上传块数/总块数),提升用户体验。

内容的提问来源于stack exchange,提问作者Andrew C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:35:23