You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Expo上传图片至Firebase时触发TypeError错误求助

解决Expo ImagePicker上传Firebase Storage报错:storage.ref is not a function

这个错误核心原因是Firebase v9+采用模块化API,不再支持旧版命名空间式调用,同时可能存在Storage实例初始化或导入错误。以下是具体修复步骤:

1. 修正Firebase配置文件(Firebase.js)

确保正确导入并初始化Storage模块:

import { initializeApp } from 'firebase/app';
import { getStorage } from 'firebase/storage';

// 你的Firebase配置信息
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// 初始化Firebase App
const app = initializeApp(firebaseConfig);
// 初始化Storage实例并导出
const storage = getStorage(app);

export { storage };

2. 修正ImageUpload组件的上传逻辑

需要将Expo ImagePicker返回的URI转换为Blob,同时使用Firebase模块化API完成上传:

import { useState } from 'react';
import { Button, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage';
import { storage } from './Firebase';

export default function ImageUpload() {
  const [imageUri, setImageUri] = useState(null);

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled) {
      setImageUri(result.assets[0].uri);
      await uploadImage(result.assets[0].uri);
    }
  };

  const uploadImage = async (uri) => {
    try {
      // 将本地URI转换为Blob对象
      const response = await fetch(uri);
      const blob = await response.blob();
      // 生成唯一存储路径和文件名
      const fileName = `images/${Date.now()}_${Math.random().toString(36).substring(2, 10)}.jpg`;
      // 创建Storage引用
      const storageRef = ref(storage, fileName);
      // 启动上传任务
      const uploadTask = uploadBytesResumable(storageRef, blob);

      // 监听上传状态
      uploadTask.on('state_changed', 
        (snapshot) => {
          const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log('上传进度:', progress);
        }, 
        (error) => {
          console.error('上传失败:', error);
        }, 
        () => {
          // 上传完成后获取文件下载链接
          getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
            console.log('文件可用链接:', downloadURL);
          });
        }
      );
    } catch (error) {
      console.error('上传处理出错:', error);
    }
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button title="选择图片并上传" onPress={pickImage} />
    </View>
  );
}

关键注意点

  • 必须使用Firebase v9+模块化API:用getStorage初始化实例,ref创建存储引用,uploadBytesResumable执行上传
  • Expo ImagePicker返回的是本地URI,无法直接传入Firebase上传方法,需先转换为Blob对象
  • 确保Firebase配置中的storageBucket填写正确,否则会导致Storage连接失败

内容的提问来源于stack exchange,提问作者tanaya sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:52:25