Skip to content

Instantly share code, notes, and snippets.

@raditotev
Last active January 13, 2022 17:24
Show Gist options
  • Save raditotev/64c3dfe0cc1cf9692e43c61130a02b55 to your computer and use it in GitHub Desktop.
Save raditotev/64c3dfe0cc1cf9692e43c61130a02b55 to your computer and use it in GitHub Desktop.
Uploading files to Firebase/ Storage using Nodejs, express and multer with diskStorage as storage option
const fs = require('fs/promises');
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const createError = require('http-errors');
const bodyParser = require('body-parser');
const { initializeApp } = require('firebase/app');
const {
getStorage,
ref,
uploadBytes,
getDownloadURL,
} = require('firebase/storage');
const multer = require('multer');
const app = express();
// Firestore setup
const { API_KEY, AUTH_DOMAIN, PROJECT_ID, BUCKET, SENDER_ID, APP_ID } =
process.env;
const firebaseConfig = {
apiKey: API_KEY,
authDomain: AUTH_DOMAIN,
projectId: PROJECT_ID,
storageBucket: BUCKET,
messagingSenderId: SENDER_ID,
appId: APP_ID,
};
const firebaseApp = initializeApp(firebaseConfig);
const firestore = getStorage(firebaseApp);
// Multer setup
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'tmp/');
},
filename: (req, file, cb) => {
cb(null, new Date().getTime() + '-' + file.originalname);
},
});
const upload = multer({ storage });
// Middleware
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
// Routes
app.post('/products', upload.single('image'), async (req, res, next) => {
try {
const file = await fs.readFile(req.file.path);
const imageRef = ref(firestore, 'products/' + req.file.filename);
const snapshot = await uploadBytes(imageRef, file);
const imageURL = await getDownloadURL(snapshot.ref);
// Remove file from /tmp folder after it has been uploaded
fs.unlink(req.file.path);
res.status(200).send(imageURL);
} catch (error) {
return next(createError(502, error.message));
}
});
// Non existing routes
app.use((req, res, next) => {
const error = new createError.NotFound();
next(error);
});
// Error handling
app.use((error, req, res, next) => {
res
.status(error.status || 500)
.json({ message: error.message || 'Server error' });
});
app.listen(process.env.PORT || 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment