Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS .NET Core Lambda - Image Upload Broken

I'm in the process of building a Web API with AWS Lambda using .NET Core.

I have run into a problem, where the code piece below work as expected on my Windows machine (Echo the image back), but when deployed to AWS Lambda, the returned image is broken. After further investigation, the echoed back file's size is nearly double the size of the sending file when deployed on 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);
    }
}

Am I missing some configuration or overlooking something? AWS Gateway??

(I'm testing the issue via Postman)

like image 268
SOK Avatar asked Jul 08 '26 20:07

SOK


1 Answers

Incase anyone is looking for a solution, in addition to adding "multipart/form-data" as binary media type in the API Gateway settings, you need to add a model in the method request body of the resource.

Details can be found at https://github.com/aws/aws-lambda-dotnet/issues/635#issuecomment-616226910

Steps:

  • Add "multipart/form-data" as binary type in LambdaEntryPoint.cs file (if that is how it is named).
    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>();
        }
    }
  • Add BinaryMediaTypes in the settings section of the AWS API Gateway as shown here - BinaryMediaTypes in API Gateway.
  • Create a new model for the API Gateway with the configuration as
{
   "$schema": "http://json-schema.org/draft-04/schema#",
   "title": "MediaFileUpload",
   "type": "object",
   "properties": {
   "file": { "type": "string" }
  }
}
  • Update the method request step by adding an entry in "Request Body" using the created model as a content type of "multipart/form-data"( as shown in API Gateway Resource).
  • Make sure that you deploy the API so that the changes take effect.

EDIT: Added code, and additional steps for clarity, as comment by @JeremyCaney

like image 181
Fasika Avatar answered Jul 11 '26 12:07

Fasika