Skip to content

Instantly share code, notes, and snippets.

@jasonpolites
Last active December 5, 2017 18:05
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/b73e27cf696de615fa110440b5d0a708 to your computer and use it in GitHub Desktop.
Save jasonpolites/b73e27cf696de615fa110440b5d0a708 to your computer and use it in GitHub Desktop.
Uploading files using GCF. The following example uses the busboy npm module, but you can use any valid multipart parser module that takes a Buffer as input.
/**
* Copyright 2017, Google, Inc.
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
exports.uploadFile = (req, res) => {
if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
// This object will accumulate all the uploaded files, keyed by their name.
const uploads = {}
const tmpdir = os.tmpdir();
// This callback will be invoked for each file uploaded.
busboy.on('file', (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.
const filepath = path.join(tmpdir, filename)
uploads[fieldname] = filepath;
file.pipe(fs.createWriteStream(filepath));
});
// This callback will be invoked after all uploaded files are saved.
busboy.on('finish', () => {
// *** Process uploaded files here ***
for (const name in uploads) {
const file = uploads[name];
fs.unlinkSync(file);
}
res.end();
});
// The raw bytes of the upload will be in req.rawBody. Send it to busboy, and get
// a callback when it's finished.
busboy.end(req.rawBody);
} else {
// Client error - only support POST.
res.status(405).end();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment