Skip to content

Instantly share code, notes, and snippets.

@jasonpolites
Last active November 15, 2017 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonpolites/ff744cfe6ab0ef1d12a94e68a036c7fc to your computer and use it in GitHub Desktop.
Save jasonpolites/ff744cfe6ab0ef1d12a94e68a036c7fc to your computer and use it in GitHub Desktop.
File Uploads in GCF
Hello World!
const path = require('path'),
os = require('os'),
fs = require('fs'),
Busboy = require('busboy');
exports.uploadFile = (req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
let saveTo;
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
// Note that os.tmpDir() is an in-memory file system, so should only
// be used for files small enough to fit in memory
saveTo = path.join(os.tmpDir(), path.basename(fieldname));
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
// Read the file back to make sure it was written
fs.readFile(saveTo, 'utf8', function(err, data) {
if (err) {
console.error(err);
res.status(500).send(err);
return;
}
res.send(`Upload Complete: ${data}`);
});
});
// The raw bytes of the upload will be in req.rawBody
busboy.end(req.rawBody);
} else {
// Only support POST
res.status(405).end();
}
}
{
"name": "upload",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"deploy": "gcloud beta functions deploy uploadFile --stage-bucket gcf-stage --trigger-http"
},
"author": "",
"license": "ISC",
"dependencies": {
"busboy": "^0.2.14"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment