javascript - 如何将 Firebase Storage 与 Cloud Firestore 连接,以便我的图片与各自的帖子相关联?

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

我有一个 CRUD React 应用程序,您可以在其中创建文章。有“标题”、“内容”和“图像”。
我在 Cloud Firestore 中有一个名为“文章”的集合。这些文档具有以下字段:“标题”和“内容”,因此每次我在我的 react 应用程序中创建文章时,都会创建一个新文档。
下一步是能够将图像添加到文章中。
我设法连接到 Firebase 并将图像从我的 React 页面上传到 Firebase 存储。但是,我如何将图像连接到他们的文章?比如,如何在 Cloud Firestore 和 Storage 之间建立连接?
我是否在我的文档中创建了一个名为“图像”的额外字段?但是那我该如何引用呢?
我也想尽量避免重复。

UploadImage.js


import React, { useState, Component } from "react";
import { storage } from "../Firebase";

function UploadFile() {
        const [image, setImage] = useState(null);
        const [url, setUrl] = useState("");
        const [progress, setProgress] = useState(0);

        const handleChange = e => {
            if (e.target.files[0]) {
              setImage(e.target.files[0]);
            }
          };

          const handleUpload = () => {
            const uploadTask = storage.ref(`images/${image.name}`).put(image);
            uploadTask.on(
              "state_changed",
              snapshot => {
                const progress = Math.round(
                  (snapshot.bytesTransferred / snapshot.totalBytes) * 100
                );
                setProgress(progress);
              },
              error => {
                console.log(error);
              },
              () => {
                storage
                  .ref("images")
                  .child(image.name)
                  .getDownloadURL()
                  .then(url => {
                    setUrl(url);
                  });
              }
            );
          };

          console.log("image: ", image);

      return (
        <div>
      <progress value={progress} max="100" />
      <br />
      <br />
      <input type="file" onChange={handleChange} />
      <button onClick={handleUpload}>Upload</button>
      <br />
      {url}
      <br />
      <img src={url || "http://via.placeholder.com/300"} alt="firebase-image" />
    </div>
         
      );
    }

    export default UploadFile;
这是我的“添加文章”表格-->

AddArticle.js

import React, { Component } from 'react';
import firebase from '../Firebase';
import UploadFile from '../components/UploadFile';

class AddArticle extends Component {

  constructor() {
    super();
    this.ref = firebase.firestore().collection('articles');
    this.state = {
      title: '',
      content: ''
    };
  }
  onChange = (e) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

  onSubmit = (e) => {
    e.preventDefault();

    const { title, content } = this.state;

    this.ref.add({
      title,
      content

    }).then((docRef) => {
      this.setState({
        title: '',
        content: ''
      });
      this.props.history.push("/")
    })
    .catch((error) => {
      console.error("Error adding document: ", error);
    });
  }

  render() {
    const { title, content } = this.state;
    return (
      <div className="container">
      <br></br><br></br><br></br>
        <div className="panel panel-default">
          <div className="panel-heading">
            <h3 className="panel-title text-center">
              Create a new article
            </h3>
          </div>
          <br></br><br></br>
          <div className="panel-body">
            <form onSubmit={this.onSubmit}>
              <div className="form-group">
                <label for="title">Title:</label>
                <input type="text" className="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" />
              </div>
              <div className="form-group">
                <label for="content">Content:</label>
                <textArea className="form-control" name="content" onChange={this.onChange} placeholder="Content" cols="80" rows="20">{content}</textArea>
              </div>
              <UploadFile />
              <button type="submit" className="btn btn-success">Submit</button>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

export default AddArticle;

最佳答案

这实际上很简单,要实现这一点,请按照以下步骤操作:

  • 将图像上传到 firebase 存储后,您应该获得该特定图像的下载 url(我在下面链接了 firebase 文档链接以了解如何实现该目标)。

  • https://firebase.google.com/docs/storage/web/download-files
  • 如果您现在成功地从 firebase 存储中获取下载 url,那么是时候在您的文档下创建单独的字段,例如“postImageUrl”(您可以命名任何您想要的名称)并在此字段下保存下载 url。
  • 现在您可以使用 busboy 库在您的页面中使用此下载 url 显示图像

  • https://www.npmjs.com/package/busboy
    注意:我是一名 Android 开发人员,所以我尽力提供帮助。如果您还有其他问题,请不要犹豫

    关于javascript - 如何将 Firebase Storage 与 Cloud Firestore 连接,以便我的图片与各自的帖子相关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63401193/

    相关文章:

    java - 在 Android Studio 上同步新项目时出现 Firebase 错误(ASCII 错误)

    javascript - Lodash orderBy 函数如何处理重音字符?

    javascript - React 速记条件输出错误数据

    javascript - Enzyme - 在作为 prop 传递的元素中触发事件

    javascript - Angular 2 - Firebase 在页面刷新时保持登录状态

    javascript - 对 documentId 的 Firestore 集合组查询

    javascript - findOneAndUpdate Mongoose 函数中的字符串文字问题

    javascript - 使用指向不同质量版本的源更改视频质量

    php - cometd 和 PHP : How to use Comet with a PHP Chat System?

    reactjs - 如何在 typescript 中编写匿名函数的函数类型定义?