Created
October 31, 2016 04:40
-
-
Save jakehasler/95fa0ad7c8cf260c9365ef3c6cf0635a to your computer and use it in GitHub Desktop.
Middleware for uploading image using the Google Cloud Storage Library
This file contains hidden or 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
'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