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

.NET API Lambda代理集成API Gateway下载S3文件损坏排查

问题:XLSX文件经API Gateway从S3下载后损坏,体积变大无法打开

问题现象

  • XLSX文件上传至S3后,通过API Gateway下载得到的文件损坏,无法正常打开
  • 下载文件体积大于原文件:响应头中content-length为29248,而原文件实际大小对应x-amzn-remapped-content-length为21934

已做配置与尝试(无效)

  • 已在API Gateway控制台配置application/vnd.openxmlformats-officedocument.spreadsheetml.sheet类型的二进制支持
  • Lambda入口已注册该文件类型的Base64编码处理:
protected override void Init(IWebHostBuilder builder)
{
    RegisterResponseContentEncodingForContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ResponseContentEncoding.Base64);
    builder.UseStartup<Startup>();
}

S3文件获取逻辑代码

public async Task<GetObjectResponse> DownloadFileAsS3ObjectAsync(string fileObjectKey, string bucketName)
{
    var getObjectRequest = new GetObjectRequest
    {
        BucketName = bucketName,
        Key = fileObjectKey
    };
    var response = await _iAmazonS3.GetObjectAsync(getObjectRequest);
    if (response.HttpStatusCode == HttpStatusCode.OK)
    {
        return response;
    }
    throw new FileNotFoundException($"The document '{fileObjectKey}' is not found");
}

API控制器下载接口代码

[HttpGet]
[ProducesResponseType(typeof(File), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)]
[SwaggerOperation(OperationId = "DownloadFile")]
public async Task<IActionResult> DownloadFileAsync([FromQuery] string fileObjectKey)
{
    _logger.LogInformation("Downloading file {File} from Bucket {BucketName}", fileObjectKey,
        _configuration["IngestionBucketName"]);
    try
    {
        var file = await _s3Client.DownloadFileAsS3ObjectAsync(fileObjectKey, _configuration["IngestionBucketName"]);

        return File(file.ResponseStream, file.Headers.ContentType, fileObjectKey.Split("/").Last());
    }
    catch (FileNotFoundException fne)
    {
        _logger.LogCritical("Error downloading file: {Error}", fne.Message);
        return NotFound();
    }
}

API Gateway响应头信息

content-disposition: attachment;filename=XXXXX.xlsx; filename*=UTF-8''XXXXX.xlsx
content-length: **29248**
content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
date: Tue, 31 Jan 2023 16:35:33 GMT
x-amz-apigw-id: fnd1YGPsDoEFqkg=
x-amzn-remapped-content-length: **21934**

希望有遇到过相同问题的朋友指点,排查是否遗漏了关键配置项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:10:15