LoginSignup
2
1

More than 3 years have passed since last update.

Lambdaプロキシ統合でmultipartのフォームデータをパースする

Posted at

ファイル添付とかmultipartで送信されてくることがあるので、そのパース方法。
busboyというライブラリを次のように使うことで実現可能。

eventはlambda関数の入力。

    if (event.headers['content-type'] && (event.headers['content-type'] as string).includes('multipart/form-data')) {
        console.log('IT IS MULTIPART');
        const input: CreateMeProfileInput = {};
        const busboy = new Busboy({
            headers: event.headers,
            defCharset: 'utf8'
        });
        return new Promise((resolve, reject) => {
            busboy.on('file', (fieldname: any, file: any, filename: any, encoding: any, mimetype: any) => {
                console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
                file.on('data', function (data: any) {
                    util.inspect(data);
                    console.log(typeof data);
                    console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
                });
                file.on('end', function () {
                    console.log('File [' + fieldname + '] Finished');
                });
            });
            busboy.on('field', function (fieldname: string, value: any, fieldnameTruncated: any, valTruncated: any, encoding: any, mimetype: any) {
                console.log(util.inspect(value));
                console.log(value.toString('utf8'));
                console.log('Field [' + fieldname + ']: value: ' + util.inspect(value) + ` encoding:${encoding}, valTruncated:${valTruncated}, mimetype:${mimetype}`);
            });
            busboy.on('finish',  () => {
                console.log('Done parsing form!');
                console.log(input);
                resolve(input);
            });
            // @ts-ignore
            busboy.on('error',  (err) => {
                console.log('busboy parse error');
                console.log(input);
                reject(err);
            });
            busboy.write(event.body); // 第二引数いらない
            busboy.end();
        });
    } 
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1