Firebase Storage调用storage.ref触发TypeError: storage.ref is not a function怎么解决?
解决方案
错误原因
你当前的const storage = firebase.storage;写法获取的是Firebase Storage的服务构造函数,不是可操作的实例对象,因此不存在ref实例方法,调用时就会触发TypeError: storage.ref is not a function报错。
修复方案
方案1:适配Firebase Web SDK v8 版本(命名空间写法)
仅需要修改Storage实例的初始化代码即可:
将原有代码:
const storage = firebase.storage;
修改为:
const storage = firebase.storage();
额外优化提示:Math.random()本身不支持传参,你现有代码生成的还是0~1区间的随机数,建议修改为const imageName = Math.floor(Math.random() * 1000000); 降低文件名重复概率。
方案2:适配Firebase Web SDK v9/v10 版本(模块化写法)
如果使用的是新版模块化SDK,原有命名空间式写法不兼容,需要替换为对应模块化API:
// 顶部导入Storage相关API import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage"; // 初始化Storage实例 const storage = getStorage(); // 调整后的上传逻辑 const handleUpload = () => { const imageName = Math.floor(Math.random() * 1000000); if (image) { const storageRef = ref(storage, `images/${imageName}.jpg`); const uploadTask = uploadBytesResumable(storageRef, image); uploadTask.on( 'state_changed', (snapshot) => { const progressP = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100); setProgress(progressP); }, (error) => { console.log(error); }, () => { getDownloadURL(uploadTask.snapshot.ref).then((imageUrl) => { db.collection('posts').add({ timestamp: firebase.firestore.FieldValue.serverTimestamp(), caption: caption, photoUrl: imageUrl, username: user.email.replace('@gmail.com', '').replace('.', ''), picUrl: user.photoURL, }); }); }, ); } };
内容的提问来源于stack exchange,提问作者Vivaan4
相关产品推荐
相关产品推荐

