Skip to content

Instantly share code, notes, and snippets.

@iirving
Last active April 23, 2024 12:18
Show Gist options
  • Save iirving/7f3589c6fcb4131d0dfb3d0b9c75fcc7 to your computer and use it in GitHub Desktop.
Save iirving/7f3589c6fcb4131d0dfb3d0b9c75fcc7 to your computer and use it in GitHub Desktop.
Upload a file binary to firebase storage
// using LTS version of node v20.x, and the firebase-admin version 12.0.0
import { initializeApp, applicationDefault } from "firebase-admin/app";
import { getStorage } from "firebase-admin/storage";
/***
* Upload a file binary to firebase storage
* @param {Buffer} fileBinary - the buffer of the file to upload
* @param {string} fileNameForUpload - the name of the file after upload
* @returns {object} - {status: string, msg: string, error: string}
*/
const uploadBinary = async (fileBinary, fileNameForUpload) => {
let result = {};
try {
const project_id = "your-project-id-here ";
const app = await initializeApp({
credential: applicationDefault(),
projectId: project_id,
appName: project_id,
storageBucket: `${project_id}.appspot.com`,
});
const buffer = await Buffer.from(fileBinary);
// optional metadata
const metadata = {
//update to refelect the binary file type/subtype
// common example are:
// image/jpeg application/msword text/csv application/json video/mp4 application/pdf
contentType: "image/gif",
};
const storage = await getStorage();
const file = await storage.bucket().file(`${fileNameForUpload}`);
await file
.save(buffer, {
metadata: metadata,
})
.then(() => {
console.log(`${filename} uploaded to firebase storage`);
result = {
status: "ok",
msg: `${fileNameForUpload} uploaded to firebase storage`,
};
})
.catch((e) => {
const msgStr = `Error uploading file to firebase storage'`;
console.error(msgStr, e);
result = {
status: "error",
msg: msgStr,
error: `${e}`,
};
});
} catch (error) {
const msgStr = `Error uploading file to firebase storage'`;
console.error(msgStr, error);
result = {
status: "error",
msg: msgStr,
error: `${error}`,
};
}
return result;
};
export { uploadBinary };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment