.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
相关产品推荐
相关产品推荐

