Created
December 16, 2021 12:03
-
-
Save fragaLY/76907dc021b670ffd5c41cf014183100 to your computer and use it in GitHub Desktop.
Storing Image and Video Files in Cloud Storage
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
'use strict'; | |
const Storage = require('@google-cloud/storage'); | |
const config = require('../config'); | |
const GCLOUD_BUCKET = config.get('GCLOUD_BUCKET'); | |
const storage = Storage({ | |
projectId: config.get('GCLOUD_PROJECT') | |
}); | |
const bucket = storage.bucket(GCLOUD_BUCKET); | |
function sendUploadToGCS(req, res, next) { | |
if (!req.file) { | |
return next(); | |
} | |
const oname = Date.now() + req.file.originalname; | |
const file = bucket.file(oname); | |
const stream = file.createWriteStream({ | |
metadata: { | |
contentType: req.file.mimetype | |
} | |
}); | |
stream.on('error', (err) => { | |
req.file.cloudStorageError = err; | |
next(err); | |
}); | |
stream.on('finish', () => { | |
file.makePublic().then(() => { | |
req.file.cloudStoragePublicUrl = `https://storage.googleapis.com/${GCLOUD_BUCKET}/${oname}`; | |
next(); | |
}); | |
}); | |
stream.end(req.file.buffer); | |
} | |
// Multer handles parsing multipart/form-data requests. | |
// This instance is configured to store images in memory. | |
// This makes it straightforward to upload to Cloud Storage. | |
const Multer = require('multer'); | |
const multer = Multer({ | |
storage: Multer.MemoryStorage, | |
limits: { | |
fileSize: 40 * 1024 * 1024 // no larger than 40mb | |
} | |
}); | |
module.exports = { | |
sendUploadToGCS, | |
multer | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment