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

后端 未结 4 1814
梦毁少年i
梦毁少年i 2020-12-14 17:55

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 g

4条回答
  •  眼角桃花
    2020-12-14 18:24

    This worked for me - using busboy

    credits owed to Parse multipart/form-data from Buffer in Node.js which I copied most of this from.

    const busboy = require('busboy');
    
    const headers = {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'OPTIONS, POST',
      'Access-Control-Allow-Headers': 'Content-Type'
    };
    
    function handler(event, context) {
      var contentType = event.headers['Content-Type'] || event.headers['content-type'];
      var bb = new busboy({ headers: { 'content-type': contentType }});
    
      bb.on('file', function (fieldname, file, filename, encoding, mimetype) {
        console.log('File [%s]: filename=%j; encoding=%j; mimetype=%j', fieldname, filename, encoding, mimetype);
    
        file
        .on('data', data => console.log('File [%s] got %d bytes', fieldname, data.length))
        .on('end', () => console.log('File [%s] Finished', fieldname));
      })
      .on('field', (fieldname, val) =>console.log('Field [%s]: value: %j', fieldname, val))
      .on('finish', () => {
        console.log('Done parsing form!');
        context.succeed({ statusCode: 200, body: 'all done', headers });
      })
      .on('error', err => {
        console.log('failed', err);
        context.fail({ statusCode: 500, body: err, headers });
      });
    
      bb.end(event.body);
    }
    
    module.exports = { handler };
    

提交回复
热议问题