child() 不是函数图片上传 firebase SDK Ver9 for Web (JavaScript)

child() is not a function image upload firebaseSDK Ver9 for Web (JavaScript)

我想做什么

我想将图片上传到 firebase 存储中的 /images 目录。

我仍然无法在文档中找到版本 9 的示例,所以如果您知道,请告诉我。

正在发生的错误

未捕获类型错误:storage.child 不是函数。

版本

源代码

我的-firebase.js

import { initializeApp } from "firebase/app";
import { getStorage, ref, list, uploadBytes } from "firebase/storage"
...
const firebaseConfig = {
  apiKey: "****",
  authDomain: "****",
  projectId: "****",
  storageBucket: "****",
  messagingSenderId: "****",
  appId: "****"
};

const firebaseApp = initializeApp(firebaseConfig);
export const storage = getStorage(firebaseApp);

api.js


import { doc, getDoc, collection, addDoc, getDocs, updateDoc, deleteDoc, query, where, orderBy, limit } from "firebase/firestore";
import { ref, list, uploadBytes } from "firebase/storage"
import { db, storage } from './firebase';

export const postDiary = async(rate = 0, body = '', uid = '', image = null) => {
  try {
    if( image ){
      const uploadRef = ref(storage);
      // ↓ error
      uploadBytes(uploadRef.child('/images/'), image).then(function(snapshot) {
        console.log(snapshot);
        console.log('Uploaded a blob or file!');
      });
    }
    const docRef = await addDoc(collection(db, "diaries"), {
      rate: rate,
      body: body,
      uid: uid,
      createdAt: dayjs().format('YYYY/MM/DD HH:mm:ss'),
      updatedAt: dayjs().format('YYYY/MM/DD HH:mm:ss')
    });
...

我试过的

if( image ){
      const uploadRef = ref(storage).child('/images/');
      // console.log(ref);
      uploadBytes(uploadRef, image).then(function(snapshot) {
        console.log(snapshot);
        console.log('Uploaded a blob or file!');
      });
    }
if( image ){
      const uploadRef = ref(storage.child('/images/'));
      // console.log(ref);
      uploadBytes(uploadRef, image).then(function(snapshot) {
        console.log(snapshot);
        console.log('Uploaded a blob or file!');
      });
    }

storage.child(...) 构造来自 Firebase SDK 8 及更早版本。您不能将其与 v9.

的新 modular/functional 语法混合和匹配

新语法中的等价物是:

uploadBytes(ref(uploadRef, '/images/'), image).then(function(snapshot) {
  ...

对于此类情况,我建议将参考文档放在手边。在这种情况下,您需要查看 ref function.