Skip to content

Instantly share code, notes, and snippets.

@stardustxx
Last active January 7, 2023 22:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stardustxx/58748550699228174b805aaadfc98a35 to your computer and use it in GitHub Desktop.
Save stardustxx/58748550699228174b805aaadfc98a35 to your computer and use it in GitHub Desktop.
Nodejs Firebase Storage Sample
const express = require('express');
const app = express();
const googleStorage = require('@google-cloud/storage');
const Multer = require('multer');
const storage = googleStorage({
projectId: "<Firebase Project ID",
keyFilename: "<path to service accounts prviate key JSON>"
});
const bucket = storage.bucket("<Firebase Storage Bucket URL");
const multer = Multer({
storage: Multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
}
});
app.listen(3000, () => {
console.log('App listening to port 3000');
});
/**
* Adding new file to the storage
*/
app.post('/upload', multer.single('file'), (req, res) => {
console.log('Upload Image');
let file = req.file;
if (file) {
uploadImageToStorage(file).then((success) => {
res.status(200).send({
status: 'success'
});
}).catch((error) => {
console.error(error);
});
}
});
/**
* Upload the image file to Google Storage
* @param {File} file object that will be uploaded to Google Storage
*/
const uploadImageToStorage = (file) => {
return new Promise((resolve, reject) => {
if (!file) {
reject('No image file');
}
let newFileName = `${file.originalname}_${Date.now()}`;
let fileUpload = bucket.file(newFileName);
const blobStream = fileUpload.createWriteStream({
metadata: {
contentType: file.mimetype
}
});
blobStream.on('error', (error) => {
reject('Something is wrong! Unable to upload at the moment.');
});
blobStream.on('finish', () => {
// The public URL can be used to directly access the file via HTTP.
const url = format(`https://storage.googleapis.com/${bucket.name}/${fileUpload.name}`);
resolve(url);
});
blobStream.end(file.buffer);
});
}
@lemissel
Copy link

Something is wrong! Unable to upload at the moment.ReferenceError: format is not defined

fi-sm: You shoud import const {format} = require('util');

@ssshreyans26
Copy link

what does blobstream do?

@lemissel
Copy link

blobstream is a variable that contains the stream of the blob data of your file... blobstream "mount" or "transform" blob data in your file....

See https://developer.mozilla.org/pt-BR/docs/Web/API/Streams_API

@TytNguyen
Copy link

The picture I upload to firebase is successful, but it can not loading, and when I connect to the picture link, it said:

AccessDenied
Access denied.

Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
How can I fix this

@ParmarTarun
Copy link

ParmarTarun commented Jan 7, 2023

The picture I upload to firebase is successful, but it can not loading, and when I connect to the picture link, it said: AccessDenied Access denied.

Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
How can I fix this

You may modify the url value to something like this for an expirable public url
const url = fileUpload.getSignedUrl({ action: "read", expires: "02-02-2025", });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment