Serverless I image upload to S3 broken after deploy, local worked only
Asked Answered
L

2

7

I trying to upload an image to S3 uses serverless and NodeJS but something wrong after upload. In local uses serverless-offline everything worked like champ but after deploy I got this error. Then I tried to intercept and detect what's happened and see this result:

Some strange character appeared in image body such as <0x0a> 0x01 0x04

enter image description here

I also tried to use serverless-apigw-binary but not luck.

Listel answered 3/4, 2020 at 0:24 Comment(8)
did you use API gateway in front of your AWS Lambda? How you call the serverless function?Apogeotropism
Yes, and I am using NestJS. Something like return serverless.proxy(server, event, context);Listel
no, what I mean is AWS API Gateway, you will need to allow file type @ AWS API Gateway if you're using it.Apogeotropism
Yes, I am using AWS API Gateway.Listel
I just found the solution. Thank @ApogeotropismListel
I am facing the same issue and i am also using Nest js with aws-serverless-express, did you find a solution ?Archducal
See my answered below.Listel
@BinhHo you can mark your self-answer as correct in order to bring more attention to it. (I believe)Hudspeth
L
8

Self Answer

Very lucky I just found the solution at binary-media-types

Add this to serverless.yml.

provider:
  # others
  apiGateway:
    binaryMediaTypes:
      - '*/*'

No need serverless-apigw-binary

No need this as well

const binaryMimeTypes = [
  'image/gif',
  'image/png',
  'image/jpeg',
  'image/jpg',
];
...

return serverless.createServer(expressApp, null, binaryMimeTypes)
Listel answered 3/4, 2020 at 0:51 Comment(4)
Should I add headers in the request? I am blocked in #69811251 Could you please help me on thisGutty
You can try to debug what happened by console.log blob file on API side. Or download uploaded file and check file content/info and see what's happening.Listel
serverless not supporting this.Gutty
Thank you @BinhHo, serverless config for API Gateway saved me. I had set the setting in the UI but it did not take... unless there is somekind of enforcement that I am unaware of. Anyway thank you!Hudspeth
P
6

Following method worked for me.

If want to upload file through lambda, one way is to open your AWS API Gateway console.

Go to

"API" -> {YourAPI} -> "Settings"

There you will find "Binary Media Types" section.

Add following media type:

multipart/form-data

Save your changes.

Then Go to "Resources" -> "proxy method"(eg. "ANY") -> "Method Request" -> "HTTP Request Headers" and add following headers "Content-Type", "Accept".

Finally deploy your api.

For more info visit: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html

Palomino answered 9/7, 2020 at 16:15 Comment(1)
The best Answer I can seeMilda

© 2022 - 2024 — McMap. All rights reserved.