reactjs - 如何在 React.js 中将图像上传到 Firebase 存储并同时将 URL 上传到 Firestore?

标签 reactjs firebase google-cloud-firestore firebase-storage

我是 React.js 的新手, 我正在尝试将图像上传到 Firebase 存储,并且在成功上传后我试图同时将 downloadURL 推送到 Firestore。怎么做?这是上传图片正常但 firestore 不工作的代码。

    import React, {useState, Component} from 'react';
    import firebase from "../firebase";

    const storage = firebase.storage();

    class ImageUpload extends Component {
      constructor(props) {
        super(props);
        this.state = {
          image: null,
          url: '',
          progress: 0
        }
        this.handleChange = this
          .handleChange
          .bind(this);
          this.handleUpload = this.handleUpload.bind(this);
      }
      handleChange = e => {
        if (e.target.files[0]) {
          const image = e.target.files[0];
          this.setState(() => ({image}));
        }
      }
      handleUpload = () => {
          const {image} = this.state;
          const uploadTask = storage.ref(`images/${image.name}`).put(image);
          uploadTask.on('state_changed',
          (snapshot) => {
            // progrss function ....
            const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
            this.setState({progress});
          },
          (error) => {
               // error function ....
            console.log(error);
          },
        () => {
            // complete function ....
            storage.ref('images').child(image.name).getDownloadURL().then(url => {
                console.log(url);
                this.setState({url});

//*************************** 这部分不工作(开始)*********** **********************

                const [imgURL, setImgURL] = useState('')

                firebase
                .firestore()
                .collection('notes')
                .add({
                  imgURL
                })
                .then(() => {
                  setImgURL('')
                })

//****************************** 这部分不工作(完) ******* *************************

            })
        });
      }
      render() {

        return (
          <div>
          <progress value={this.state.progress} max="100"/>
          <br/>
            <input type="file" onChange={this.handleChange}/>
            <button onClick={this.handleUpload}>Upload</button>
            <br/>

            <img src={this.state.url || 'http://via.placeholder.com/400x300'} alt="Uploaded images" height="300" width="400"/>
          </div>
        )
      }
    }
    export default ImageUpload;

最佳答案

要将下载URL写入数据库,你不需要将其存储在状态中。您可以直接在 then 处理程序中将其写入数据库:

storage.ref('images').child(image.name).getDownloadURL().then(url => {
    firebase
    .firestore()
    .collection('notes')
    .add({
      imgURL: url
    })
    .then(() => {
      setImgURL('')
    })
});

关于reactjs - 如何在 React.js 中将图像上传到 Firebase 存储并同时将 URL 上传到 Firestore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61215555/

相关文章:

java - 将所有字段名称从 firestore 文档获取到 arraylist

firebase - Flutter/Firestore- 'List<dynamic>'类型不是 'Widget'类型的子类型

javascript - react |提升状态后如何控制子组件

javascript - JSX 与 ES6/ES2015

java - Java代码注释中使用方括号的目的是什么?

ios - 如何为 Swift 配置 Firebase 并读取数据

android - react-native gradle config 和 react-native-firebase 最新版本不匹配

firebase - 如何在不知道键的情况下强制执行 Firestore 规则中映射中的值?

reactjs - React componentDidMount() 在未安装的组件上被触发

reactjs - 无法从 AssyncStorage 检索数据