简体   繁体   English

从 lambda (Nodejs) 上传 multipart/form-data 到 S3

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

I want to upload multipart/form-data file to S3 using Nodejs.我想使用 Nodejs 将 multipart/form-data 文件上传到 S3。

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.我能够从 lambda 将内容写入 S3,但是当文件从 S3 下载时,它已损坏。

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:以下是我的 lambda 代码:

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
        })
    };
}

If want to upload file through lambda, one way is to open your AWS API Gateway console.如果想通过 lambda 上传文件,一种方法是打开您的 AWS API Gateway 控制台。

Go to

"API" -> {YourAPI} -> "Settings" “API” -> {YourAPI} -> “设置”

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".然后转到“资源”->“代理方法”(例如“任何”)->“方法请求”->“HTTP 请求标头”并添加以下标头“内容类型”、“接受”。

Finally deploy your api.最后部署你的api。

For more info visit: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html有关更多信息,请访问: https : //docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html

There are 2 possible points of failure - Lambda receives corrupted data or you corrupt data while sending it to S3.有 2 个可能的故障点 - Lambda 接收到损坏的数据,或者您在将数据发送到 S3 时损坏了数据。

Sending multipart/form-data content to Lambda is not straightforward.将 multipart/form-data 内容发送到 Lambda 并不简单。 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).完成此操作并确定 Lambda 中的数据正确后,请检查是否将其正确发送到 S3(请参阅 S3 文档和示例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM