Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle multipart/form-data with Serverless?

How to handle multipart/form-data with serverless-framework? v.0.5.6

Just tried this:

"requestTemplates": {
        "multipart/form-data": {
          "httpMethod": "$context.httpMethod",
          "body": "$input.json('$')",
          "queryParams": "$input.params().querystring",
          "headerParams": "$input.params().header",
          "headerParamNames": "$input.params().header.keySet()",
          "contentTypeValue": "$input.params().header.get('Content-Type')"
        },
        "application/json": {
          "httpMethod": "$context.httpMethod",
          "body": "$input.json('$')",
          "queryParams": "$input.params().querystring",
          "headerParams": "$input.params().header",
          "headerParamNames": "$input.params().header.keySet()",
          "contentTypeValue": "$input.params().header.get('Content-Type')"
        }
      }

action.js:

export function respond(event, cb) {

    var form = new formidable.IncomingForm();
    form.parse(event, function(err, fields, files) {
        if (err == null) {
            var response = {
                status: "true",
                data: fields,
                error: []
            };
            return cb(null, response);
        } else {
            console.log(err);
            return cb(null, ApiErrors.errors(402, err['message'] + fields));
        }
    });



}

But got an error: errorMessage = "Cannot read property 'content-length' of undefined";

like image 934
Marckaraujo Avatar asked Feb 07 '23 04:02

Marckaraujo


1 Answers

I've got this working with serverless by emulating http.ClientRequest and using a form parser tool like formidable.

I'm using lambda-proxy for the API Gateway event configuration.

const Stream      = require('stream').Readable;
const Formidable  = require('formidable');

module.exports.upload = ( e, ctx, cb ) => {
    let form = new Formidable.IncomingForm();

    let stream = new Stream();
    stream.push( e.body );
    stream.push( null );

    // NOTE: You'll likely want to toLowerCase() at least 'Content-Type' header key
    stream.headers = e.headers;

    form.parse( stream, (err, fields, files) => {
        // Work with your parsed form results here.
    });
}
like image 146
user1835017 Avatar answered Mar 24 '23 17:03

user1835017