namespace Dpz.Core.WebApi;

/// <summary>
/// 将文件内容直接写入响应流,避免先完整缓冲到内存
/// </summary>
public sealed class StreamingFileResult(
    string contentType,
    string fileDownloadName,
    Func<Stream, CancellationToken, Task> writeAsync
) : IActionResult
{
    /// <summary>
    /// 执行文件响应写入
    /// </summary>
    /// <param name="context">Action 执行上下文</param>
    public async Task ExecuteResultAsync(ActionContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        var response = context.HttpContext.Response;
        response.ContentType = contentType;
        response.Headers.ContentDisposition =
            $"attachment; filename=\"{fileDownloadName}\"; filename*=UTF-8''{Uri.EscapeDataString(fileDownloadName)}";

        await writeAsync(response.BodyWriter.AsStream(), context.HttpContext.RequestAborted);
        await response.BodyWriter.FlushAsync(context.HttpContext.RequestAborted);
    }
}
评论加载中...