-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
69 lines (58 loc) · 1.82 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
const Busboy = require('busboy');
/*
* This module will parse the multipart-form containing files and fields from the lambda event object.
* @param {event} - an event containing the multipart-form in the body
* @return {object} - a JSON object containing array of files and fields, sample below.
{
files: [
{
filename: 'test.pdf',
content: <Buffer 25 50 6f 62 ... >,
contentType: 'application/pdf',
encoding: '7bit',
fieldname: 'uploadFile1'
}
],
field1: 'VALUE1',
field2: 'VALUE2',
}
*/
const parse = (event) => new Promise((resolve, reject) => {
const busboy = new Busboy({
headers: {
'content-type': event.headers['content-type'] || event.headers['Content-Type']
}
});
const result = {
files: []
};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const uploadFile = {};
file.on('data', data => {
uploadFile.content = data;
});
file.on('end', () => {
if (uploadFile.content) {
uploadFile.filename = filename;
uploadFile.contentType = mimetype;
uploadFile.encoding = encoding;
uploadFile.fieldname = fieldname;
result.files.push(uploadFile);
}
});
});
busboy.on('field', (fieldname, value) => {
result[fieldname] = value;
});
busboy.on('error', error => {
reject(error);
});
busboy.on('finish', () => {
resolve(result);
});
const encoding = event.encoding || (event.isBase64Encoded ? "base64" : "binary");
busboy.write(event.body, encoding);
busboy.end();
});
module.exports.parse = parse;