Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions functions/http/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,24 +166,42 @@ exports.uploadFile = (req, res) => {
fields[fieldname] = val;
});

let fileWrites = [];
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: should this be const?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think our linter would complain.


// This code will process each file uploaded.
busboy.on('file', (fieldname, file, filename) => {
// Note: os.tmpdir() points to an in-memory file system on GCF
// Thus, any files in it must fit in the instance's memory.
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
uploads[fieldname] = filepath;
file.pipe(fs.createWriteStream(filepath));

const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);

// File was processed by Busboy; wait for it to be written to disk.
const promise = new Promise((resolve, reject) => {
file.on('end', () => {
writeStream.end();
});
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
fileWrites.push(promise);
});

// This event will be triggered after all uploaded files are saved.
// Triggered once all uploaded files are processed by Busboy.
// We still need to wait for the disk writes (saves) to complete.
busboy.on('finish', () => {
// TODO(developer): Process uploaded files here
for (const name in uploads) {
const file = uploads[name];
fs.unlinkSync(file);
}
res.send();
Promise.all(fileWrites)
.then(() => {
// TODO(developer): Process saved files here
for (const name in uploads) {
const file = uploads[name];
fs.unlinkSync(file);
}
res.send();
});
});

busboy.end(req.rawBody);
Expand Down