// handler.js
"use strict";
const stream = require("stream");
const Busboy = require("busboy");
/** User upload (POST) is processed */
const handlePost = (event) => {
return new Promise((resolve, reject) => {
const busboy = new Busboy({ headers: event.headers });
let html = "";
/** The file is received */
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
let buf = Buffer.alloc(0);
console.log({ fieldname });
/** File data blocks are received and spliced into a complete buffer */
file.on("data", function (data) {
buf = Buffer.concat([buf, data]);
});
/** File data block receipt is completed, and the DOM string is generated */
file.on("end", function () {
const imgBase64 = buf.toString("base64");
html += `![](data:${mimetype};base64, ${imgBase64})`;
});
});
/** multipart/form-data receipt is completed, and the generated HTML is constructed and returned */
busboy.on("finish", function () {
console.log({ msg: "Parse form complete!", html });
resolve({
statusCode: 200,
headers: {
"content-type": "text/html",
},
body: html,
});
});
/**
* busboy needs to process the data in the form of stream pipe.
* After the body is decoded to the buffer,
* it is converted into a stream and finally piped to busboy
*/
const bodyBuf = Buffer.from(event.body, "base64");
var bufferStream = new stream.PassThrough();
bufferStream.end(bodyBuf);
bufferStream.pipe(busboy);
});
};
/** The static file is returned */
const handleGet = (event) => {
const html = `<html><head></head><body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="image-1" accept="image/*"><br />
<input type="file" name="image-2" accept="image/*"><br />
<input type="submit">
</form>
</body></html>`;
console.log({ msg: "Get form complete!", html });
return {
statusCode: 200,
headers: {
"content-type": "text/html",
},
body: html,
};
};
/** Function entry */
exports.main_handler = async (event, context) => {
const method = event.httpMethod;
/** If the request is a POST request, the user's multipart/form-data is processed and a page displaying the upload result is generated */
if (method === "POST") {
return handlePost(event);
}
/** If the request is a GET request, the page where the file is uploaded is returned */
if (method === "GET") {
return handleGet(event);
}
};
Was this page helpful?