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

后端 未结 4 1808
梦毁少年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:21

    If you want to get a ready to use object, here is the function I use. It returns a promise of it and handle errors:

    import Busboy from 'busboy';
    import YError from 'yerror';
    import getRawBody from 'raw-body';
    
    const getBody = (content, headers) =>
        new Promise((resolve, reject) => {
          const filePromises = [];
          const data = {};
          const parser = new Busboy({
            headers,
            },
          });
    
          parser.on('field', (name, value) => {
            data[name] = value;
          });
          parser.on('file', (name, file, filename, encoding, mimetype) => {
            data[name] = {
              filename,
              encoding,
              mimetype,
            };
            filePromises.push(
              getRawBody(file).then(rawFile => (data[name].content = rawFile))
            );
          });
          parser.on('error', err => reject(YError.wrap(err)));
          parser.on('finish', () =>
            resolve(Promise.all(filePromises).then(() => data))
          );
          parser.write(content);
          parser.end();
        })
    

提交回复
热议问题