Skip to content

Instantly share code, notes, and snippets.

@jakehasler
Created October 31, 2016 04:40
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 jakehasler/95fa0ad7c8cf260c9365ef3c6cf0635a to your computer and use it in GitHub Desktop.
Save jakehasler/95fa0ad7c8cf260c9365ef3c6cf0635a to your computer and use it in GitHub Desktop.
Middleware for uploading image using the Google Cloud Storage Library
'use strict';
const storage = require('@google-cloud/storage');
const fs = require('fs')
const gcs = storage({
projectId: 'your-project-id',
keyFilename: '/path/to/keyfile.json'
});
const bucketName = 'bucket-name-for-upload'
const bucket = gcs.bucket(bucketName);
function getPublicUrl(filename) {
return 'https://storage.googleapis.com/' + bucketName + '/' + filename;
}
let ImgUpload = {};
ImgUpload.uploadToGcs = (req, res, next) => {
if(!req.file) return next();
// Can optionally add a path to the gcsname below by concatenating it before the filename
const gcsname = req.file.originalname;
const file = bucket.file(gcsname);
const stream = file.createWriteStream({
metadata: {
contentType: req.file.mimetype
}
});
stream.on('error', (err) => {
req.file.cloudStorageError = err;
next(err);
});
stream.on('finish', () => {
req.file.cloudStorageObject = gcsname;
req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
next();
});
stream.end(req.file.buffer);
}
module.exports = ImgUpload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment