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

React Native上传图片到Firebase Storage取下载链接存Firestore的实现方法

解决方案

你原来的代码没有等待上传完成就结束了逻辑,也没有调用获取下载链接的方法,只需要调整逻辑,等图片上传成功后获取下载URL,再执行Firestore写入即可,修改后的完整代码如下:

const handleSubmit = async (values) => {
  try {
    const imageUri = values.images[0];
    const filename = imageUri.substring(imageUri.lastIndexOf('/') + 1);
    const response = await fetch(imageUri);
    const blob = await response.blob();

    // 1. 创建存储引用
    const storageRef = firebase.storage().ref().child(`images/${filename}`);
    // 2. 等待上传完成
    await storageRef.put(blob);
    // 3. 获取图片下载链接
    const imageUrl = await storageRef.getDownloadURL();

    // 4. 拿到链接后写入Firestore
    await firebase.firestore().collection('listings').add({
      id: uuid.v4(),
      title: values.title,
      price: values.price,
      description: values.description,
      category: values.category['label'],
      image: imageUrl,
      createdAt: new Date(),
      supplierId: user.uid
    });

    // 此处可添加上传完成的后续逻辑,例如提示成功、跳转页面等
    console.log('数据上传成功');

  } catch(e) {
    console.log('操作失败:', e);
  }
}

关键修改说明

  • 原来的on('state_changed')监听适合需要做进度展示的场景,如果你不需要实时进度,直接用await等待上传任务完成即可,逻辑更简洁
  • 上传完成后主动调用存储引用的getDownloadURL()方法,就能拿到可公开访问的图片链接
  • 把Firestore写入的逻辑移到拿到下载链接之后,保证写入的时候image字段已经有有效值
  • 所有异步操作都加了await,用外层的try catch统一捕获错误,不需要单独写错误回调

如果你需要保留上传进度监听的写法,也可以把Firestore写入逻辑放到state_changed的第三个参数(上传完成回调)里,示例如下:

storageRef.put(blob).on('state_changed', 
  (snapshot) => {
    // 这里可以计算进度,用于进度条展示
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('上传进度:' + progress + '%');
  },
  (error) => console.log('上传失败:', error),
  async () => {
    // 上传完成后获取链接,写入Firestore
    const imageUrl = await storageRef.getDownloadURL();
    await firebase.firestore().collection('listings').add({
      id:uuid.v4(),
      title: values.title,
      price: values.price,
      description: values.description,
      category: values.category['label'],
      image:imageUrl,
      createdAt: new Date(),
      supplierId:user.uid
    })
  }
)

内容的提问来源于stack exchange,提问作者Yasiru Ayeshmantha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:00:00