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

如何修改BlobDownloadToOptions代码实现在ASP.NET WebForm下载大文件到浏览器

解决方案

要在ASP.NET WebForm中实现2GB级大文件从Azure Blob直接下载到浏览器,需将原代码中写入本地文件流的逻辑改为写入HttpResponse输出流,同时保留BlobDownloadToOptions的分块传输配置来解决大文件下载问题。

修改后的代码示例(ASPX页面后台代码)

首先确保你的ASPX页面已启用异步:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DownloadBlob.aspx.cs" Inherits="YourNamespace.DownloadBlob" Async="true" %>

后台代码:

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

public partial class DownloadBlob : System.Web.UI.Page
{
    protected async void Page_Load(object sender, EventArgs e)
    {
        // 替换为你的Blob连接信息
        string connectionString = "你的Azure Blob连接字符串";
        string containerName = "存储容器名称";
        string blobName = "要下载的大文件名";

        BlobClient blobClient = new BlobClient(connectionString, containerName, blobName);

        await DownloadBlobToBrowserAsync(blobClient, Response);
        Response.End();
    }

    public static async Task DownloadBlobToBrowserAsync(BlobClient blobClient, HttpResponse response)
    {
        // 获取Blob属性,用于配置响应头
        BlobProperties blobProps = await blobClient.GetPropertiesAsync();

        // 设置浏览器下载响应头
        response.Clear();
        response.ContentType = blobProps.ContentType ?? "application/octet-stream";
        response.AddHeader("Content-Disposition", $"attachment; filename=\"{blobProps.Name}\"");
        response.AddHeader("Content-Length", blobProps.ContentLength.ToString());

        // 配置大文件分块传输参数
        var transferOptions = new StorageTransferOptions
        {
            MaximumConcurrency = 2, // 并行传输线程数
            InitialTransferSize = 8 * 1024 * 1024, // 初始分块大小8MiB
            MaximumTransferSize = 4 * 1024 * 1024 // 单块最大传输大小4MiB
        };

        var downloadOptions = new BlobDownloadToOptions()
        {
            TransferOptions = transferOptions
        };

        // 将Blob内容直接写入浏览器响应流
        await blobClient.DownloadToAsync(response.OutputStream, downloadOptions);

        // 确保流刷新并关闭
        response.Flush();
        response.OutputStream.Close();
    }
}

关键修改说明

  • 替换输出目标:把原代码的本地FileStream替换为HttpResponse.OutputStream,直接将Blob内容输出到浏览器。
  • 配置响应头:通过Content-Disposition指定下载文件名,Content-Type匹配Blob的MIME类型,Content-Length让浏览器显示下载进度。
  • 保留分块逻辑:StorageTransferOptions的配置不变,确保大文件分块传输,避免内存溢出或请求超时。
  • 异步适配:页面启用Async="true",使用async/await处理异步下载,避免阻塞服务器线程。

注意事项

  1. 若使用ASHX一般处理程序,逻辑类似,在ProcessRequestAsync方法中处理响应即可。
  2. 可根据服务器性能调整MaximumConcurrency、分块大小等参数,优化下载效率。

内容的提问来源于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 14:53:18