AWS .NET Core Lambda - 图像上传已损坏

时间:2018-04-07 08:28:44

标签: amazon-web-services asp.net-web-api amazon-s3 asp.net-core aws-lambda

我正在使用.NET Core使用AWS Lambda构建Web API。

我遇到了一个问题,下面的代码片段在我的Windows机器上按预期工作(回显图像),但是当部署到AWS Lambda时,返回的图像被破坏了。经过进一步调查后,回传文件的大小几乎是部署在AWS上时发送文件大小的两倍?

[HttpPost]
public async Task<IActionResult> Post(IFormFile file)
{
    using (var tmpStream = new MemoryStream())
    {
        await file.CopyToAsync(tmpStream);
        var fileExtension = Path.GetExtension(file.FileName);
        return File(tmpStream.ToArray(), file.ContentType);
    }
}

我错过了一些配置还是忽略了什么? AWS Gateway ??

(我正在通过Postman测试这个问题)

3 个答案:

答案 0 :(得分:2)

如果有人在寻找解决方案,除了在API Gateway设置中添加“ multipart / form-data”作为二进制媒体类型外,您还需要在资源的方法请求主体中添加模型。

有关详细信息,请访问https://github.com/aws/aws-lambda-dotnet/issues/635#issuecomment-616226910

步骤:

  • 在LambdaEntryPoint.cs文件中添加“ multipart / form-data”作为二进制类型(如果这样命名的话)。
    public class LambdaEntryPoint : APIGatewayProxyFunction
    {
        /// <summary>
        /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class
        /// needs to be configured in this method using the UseStartup<>() method.
        /// </summary>
        /// <param name="builder"></param>
        protected override void Init(IWebHostBuilder builder)
        {
            RegisterResponseContentEncodingForContentType("multipart/form-data", ResponseContentEncoding.Base64);
            builder.UseStartup<Startup>();
        }
    }
{
   "$schema": "http://json-schema.org/draft-04/schema#",
   "title": "MediaFileUpload",
   "type": "object",
   "properties": {
   "file": { "type": "string" }
  }
}
  • 通过使用创建的模型在内容的“ multipart / form-data”(如API Gateway Resource中所示的内容类型的“请求正文”中添加条目来更新方法请求步骤。
  • 确保部署API,以使更改生效。

编辑:添加了代码,并为清晰起见采取了其他步骤,如@JeremyCaney所述

答案 1 :(得分:1)

你看过文件的内容了吗?我的猜测是html错误结果或其他什么。

在这篇博文(Serverless ASP.NET Core 2.0 Applications)中,他们提到:

  

如果您的网络应用程序显示图像,我们建议您从Amazon S3提供这些图像。这对于返回静态内容(如图像,层叠样式表等)更有效。此外,将图像从Lambda函数返回到浏览器,您需要在API Gateway for binary data中执行额外配置

请参阅API Gateway for binary data了解如何配置。

答案 2 :(得分:0)

在 AWS API Gateway 的设置部分添加 BinaryMediaTypes "multipart/form-data"。部署Api(如果之前做过,改设置后再做一次)

相关问题