Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8934

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

$
0
0

ファイル添付とか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();
        });
    } 

Viewing all articles
Browse latest Browse all 8934

Trending Articles