I'm using Next.js here. I need to upload an image to my firebase storage. But it gives me a massive amount of errors. Okay, it gives me 1 error.
Init firebase admin sdk
// firebase.js
import * as admin from "firebase-admin";
import serviceAccount from "./firebase.serviceAccount.json";
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL
});
}
const firestore = admin.firestore();
const storage = admin.storage();
c
export { firestore, storage };
Uploading image
// route.js
import { storage } from "../../firebase";
const router = async (req, res) => {
// ...
// Getting file from api request and so on...
// ...
const file = <an instance of File object>;
const currentTime = Date.now();
const fileName = file.name;
const fileTitle = `${currentTime}-${fileName}`;
const metadata = {
contentType: file.type
};
const task = storage.ref().child(fileTitle).put(file, metadata);
task.then(snapshot => snapshot.ref.getDownloadURL())
.then(console.log)
.catch(console.error);
};
export default router;
Failed to import the Cloud Storage client library for Node.js. Make sure to install the "@google-cloud/storage" npm package. Original error: Error: EIO: i/o error, read
Although I've installed @google-cloud/storage in my package list
storageBucket
into your admin.initializeApp({})
if (!admin.apps.length) {
try {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
});
} catch (e) {
console.log("Failed to initialize App: " + e);
}
}
admin.storage().bucket()
instead of admin.storage()
import * as admin from "firebase-admin";
import serviceAccount from "./firebase.serviceAccount.json";
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL
});
}
const firestore = admin.firestore();
const storage = admin.storage().bucket();
export { firestore, storage };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.