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

如何从Azure Storage返回FileStreamResult?

从Azure Storage获取文件并返回FileStreamResult的实现

1. 安装依赖包

首先安装Azure Blob存储的官方SDK包:

dotnet add package Azure.Storage.Blobs

2. 配置BlobServiceClient

在ASP.NET Core的Program.cs中,将BlobServiceClient注册为单例服务,使用存储账户连接字符串:

var builder = WebApplication.CreateBuilder(args);

// 注册BlobServiceClient
builder.Services.AddSingleton(sp => 
    new BlobServiceClient(builder.Configuration.GetConnectionString("AzureStorage")));

// 其他配置...
var app = builder.Build();

同时在appsettings.json中添加Azure Storage连接字符串:

{
  "ConnectionStrings": {
    "AzureStorage": "DefaultEndpointsProtocol=https;AccountName=你的存储账户名;AccountKey=你的存储密钥;EndpointSuffix=core.windows.net"
  }
}

3. 编写控制器下载方法

在控制器中注入BlobServiceClient,实现获取Blob流并返回FileStreamResult的逻辑:

using Azure.Storage.Blobs;
using Microsoft.AspNetCore.Mvc;

namespace YourNamespace.Controllers;

[ApiController]
[Route("[controller]")]
public class FileController : ControllerBase
{
    private readonly BlobServiceClient _blobServiceClient;

    public FileController(BlobServiceClient blobServiceClient)
    {
        _blobServiceClient = blobServiceClient;
    }

    [HttpGet("download")]
    public async Task<IActionResult> Download(string containerName, string blobName)
    {
        // 获取目标容器和Blob的客户端
        var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
        var blobClient = containerClient.GetBlobClient(blobName);

        // 检查Blob是否存在
        if (!await blobClient.ExistsAsync())
        {
            return NotFound("指定文件不存在");
        }

        // 打开Blob的读取流
        var blobStream = await blobClient.OpenReadAsync();

        // 获取Blob的ContentType,若未设置可手动指定(如"application/octet-stream")
        var properties = await blobClient.GetPropertiesAsync();
        var contentType = properties.Value.ContentType ?? "application/octet-stream";

        // 返回FileStreamResult,支持浏览器直接下载或预览
        return new FileStreamResult(blobStream, contentType)
        {
            FileDownloadName = blobName // 指定下载时显示的文件名
        };
    }
}

注意事项

  • 权限验证:确保使用的连接字符串、SAS令牌或托管身份拥有目标Blob的读取权限
  • ContentType处理:如果Blob上传时未设置ContentType,可根据文件扩展名手动映射(如.pdf对应application/pdf)
  • 流的释放:FileStreamResult会自动处理流的释放,无需手动调用Dispose

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:35:01