Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - Parse multipart/form-data from body as string on AWS Lambda

I'm glad to see AWS now supports multipart/form-data on AWS Lambda, but now that the raw data is in my lambda function how do I process it?

I see multiparty is a good multipart library in Node for multipart processing, but its constructor expects a request, not a raw string.

The input message I am receiving on my Lambda function (after the body mapping template has been applied) is:

{ "rawBody": "--ce0741b2-93d4-4865-a7d6-20ca51fe2689
Content-Disposition: form-data; name="Content-Type"

multipart/mixed; boundary="------------020601070403020003080006"
--ce0741b2-93d4-4865-a7d6-20ca51fe2689
Content-Disposition: form-data; name="Date"

Fri, 26 Apr 2013 11:50:29 -0700
--ce0741b2-93d4-4865-a7d6-20ca51fe2689
Content-Disposition: form-data; name="From"

Bob <bob@mg.mydomain.io>
--ce0741b2-93d4-4865-a7d6-20ca51fe2689
Content-Disposition: form-data; name="In-Reply-To"
... 

etc and some file data.

The body mapping template I'm using is

{
  "rawBody" : "$util.escapeJavaScript($input.body).replaceAll("\'", "'")"
}

How can I parse this data to acecss the fields and files posted to my Lambda function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

busboy doesn't work for me in the "file" case. It didn't throw an exception so I couldn't handle exception in lambda at all.

I'm using aws-lambda-multipart-parser lib wasn't hard like so. It just parses data from event.body and returns data as Buffer or text.

Usage:

const multipart = require('aws-lambda-multipart-parser');

const result = multipart.parse(event, spotText) // spotText === true response file will be Buffer and spotText === false: String

Response data:

{
    "file": {
        "type": "file",
        "filename": "lorem.txt",
        "contentType": "text/plain",
        "content": {
            "type": "Buffer",
            "data": [ ... byte array ... ]
        } or String
    },
    "field": "value"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...