Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload multipart/form-data to S3 from lambda (Nodejs)

I want to upload multipart/form-data file to S3 using Nodejs.

I have tried various approaches but none of them are working. I was able to write content to S3 from lambda but when the file is downloaded from S3, it was corrupted.

Can someone provide me a working example or steps that could help me?

Thanking you in anticipation.

Please suggest another alternative if you think so.

Following is my lambda code:

export const uploadFile = async event => {
  const parser = require("lambda-multipart-parser");
  const result = await parser.parse(event);
  const { content, filename, contentType } = result.files[0];
  const params = {
    Bucket: "name-of-the-bucket",
    Key: filename,
    Body: content,
    ContentDisposition: `attachment; filename="${filename}";`,
    ContentType: contentType,
    ACL: "public-read"
  };

  const res = await s3.upload(params).promise();
  return {
        statusCode: 200,
        body: JSON.stringify({
            docUrl: res.Location
        })
    };
}
like image 229
Kedar Shinde Avatar asked Sep 08 '25 11:09

Kedar Shinde


2 Answers

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

like image 200
varad_s Avatar answered Sep 11 '25 02:09

varad_s


There are 2 possible points of failure - Lambda receives corrupted data or you corrupt data while sending it to S3.

Sending multipart/form-data content to Lambda is not straightforward. You can see how to do that here.
After you did this and you're sure your data is correct in Lambda, check if you send it to S3 correctly (see S3 docs and examples for that).

like image 37
nickolay.laptev Avatar answered Sep 11 '25 01:09

nickolay.laptev