【问题标题】:Handle multipart/form-data with Serverless?使用无服务器处理多部分/表单数据?
【发布时间】:2017-04-08 04:47:43
【问题描述】:

如何使用无服务器框架处理多部分/表单数据? v.0.5.6

刚刚试过这个:

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



}

但出现错误:errorMessage = "Cannot read property 'content-length' of undefined";

【问题讨论】:

  • 如果event 是一个常规的 Lambda 事件,那么该表单已经为您解析好了。解析来自请求的输入是请求模板的一部分。所以这个责任落在 API Gateway 身上,而不是 Lambda。

标签: multipartform-data serverless-framework


【解决方案1】:

我通过模拟http.ClientRequest 并使用formidable 之类的表单解析器工具来使用serverless

我使用lambda-proxy 进行 API Gateway 事件配置。

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

【讨论】:

  • 这对我有用,但我还必须手动设置 e.headers['content-length'] = e.body.length; 否则将使用 dummyParser!
【解决方案2】:

好吧,我无法将其设为 multipart/form-data,所以我使用了 base64 字符串。

action.js:

export function respond(event, cb) {
    //console.log('Received event:', JSON.stringify(event, null, 2));

    var key = new Date().toISOString().substr(0, 10) + '/' + String(Date.now());
    var contentType = event.body["data"].substr(0, event.body["data"].indexOf(';'));

    if (!contentType.match(/(\.|\/)(gif|jpe?g|png)$/i)) {
        return cb(null, 'invalid content type, gif, jpg, and png supported');
    }
    var data = new Buffer(event.body["data"].replace(/^image\/\w+;base64,/, ''),'base64');

    var params = {
        Bucket: 'your-bucket',
        Key: key,
        Body: data,
        ContentEncoding: 'base64',
        ContentType: contentType,
        ACL: 'public-read'
    };
    s3.upload(params, function (err, data) {
        if (err) {
            console.log(err);
            return cb(null, ApiErrors.errors(402, err['message']));
        } else {
            var response = {
                status: "true",
                data: {
                    url: urlPrefix + key
                },
                error: []
            };
            return cb(null, response);
        }
    });

}

请求模板:

"requestTemplates": {
        "application/json": {
          "httpMethod": "$context.httpMethod",
          "body": "$input.json('$')",
          "header": "$input.params().header.get($header)",
          "headerParam": "$input.params().header.keySet()",
          "contentType": "$input.params().header.get('Content-Type')"
        }
      },

【讨论】:

  • @GurpreetSinghDrish,该解决方案是无服务器 0.5。现在完全不同了。
猜你喜欢
  • 2021-02-20
  • 1970-01-01
  • 2012-11-17
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 2012-02-16
相关资源
最近更新 更多