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

ASP.NET WebForm 4.8上传1-2GB文件至Azure Blob遇内存溢出及方法咨询

解决ASP.NET WebForm 4.8大文件上传Azure Blob的OutOfMemoryException问题

问题根源

即使你已经在web.config中配置了最大文件大小,但若上传过程中把整个请求流(Request.InputStream)全部加载到内存(比如用MemoryStream缓存),1-2GB的文件会直接占满内存触发OutOfMemoryException。核心解决思路是避免内存缓存,直接将请求流流式传递给Azure Blob存储。

正确实现方式

直接使用Azure Blob SDK的流式API,分块读取请求流并写入Blob,每次仅处理一小段数据,控制内存占用:

protected void UploadLargeFile_Click(object sender, EventArgs e)
{
    // 初始化Blob客户端
    var blobServiceClient = new BlobServiceClient("your_azure_storage_connection_string");
    var containerClient = blobServiceClient.GetBlobContainerClient("your_container_name");
    var blobClient = containerClient.GetBlobClient($"uploaded_{DateTime.Now.Ticks}.bin");

    // 使用OpenWrite获取可写入的Blob流,直接对接请求流
    using var blobWriteStream = blobClient.OpenWrite(overwrite: true);
    var buffer = new byte[81920]; // 80KB缓冲区,可根据服务器内存调整
    int bytesRead;

    // 分块读取请求流并写入Blob
    while ((bytesRead = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        blobWriteStream.Write(buffer, 0, bytesRead);
        // 可选:实时更新上传进度(需配合UpdatePanel实现无刷新)
        // ProgressStatus.Text = $"已上传:{totalBytes += bytesRead} bytes";
        // ProgressStatus.Update();
    }
}

确认web.config配置

确保以下配置正确设置(对应2GB上限):

<system.web>
  <!-- maxRequestLength单位为KB,2097152 = 2GB -->
  <httpRuntime maxRequestLength="2097152" executionTimeout="3600" />
</system.web>
<system.webServer>
  <security>
    <requestFiltering>
      <!-- maxAllowedContentLength单位为字节,2147483648 = 2GB -->
      <requestLimits maxAllowedContentLength="2147483648" />
    </requestFiltering>
  </security>
</system.webServer>

BlobClient.OpenWrite()与Upload()的适用场景

BlobClient.Upload()

  • 适合小到中等大小的文件(通常几百MB以内),支持直接传入字节数组、本地文件路径或Stream。
  • SDK会自动处理分块上传(当文件大小超过默认分块大小),但如果传入的是内存中的Stream,仍会占用对应内存。
  • 用法简洁,代码量少,适合无需自定义写入逻辑、不需要实时监控上传进度的场景。
  • 示例:
    // 上传本地文件
    blobClient.Upload(@"C:\local_file.bin", overwrite: true);
    // 上传内存中的Stream(小文件适用)
    blobClient.Upload(memoryStream, overwrite: true);
    

BlobClient.OpenWrite()

  • 适合大文件流式上传(1GB以上),或无法一次性将文件加载到内存的场景。
  • 返回可写入的Stream,支持分块写入,每次仅处理一小段数据,内存占用极低。
  • 支持自定义写入逻辑、实时监控上传进度,或源数据是逐步生成/获取的场景(比如从网络流、数据库流读取后直接写入)。
  • 示例见上文的大文件上传代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:13:24