curl -F "hello_file=@hello.txt" https://us-central1-[YOUR-PROJECT].cloudfunctions.net/uploadFile
Last active
November 15, 2017 18:07
-
-
Save jasonpolites/ff744cfe6ab0ef1d12a94e68a036c7fc to your computer and use it in GitHub Desktop.
File Uploads in GCF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hello World! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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