使用Firebase实时数据库和React将图像上传给用户 [英] Upload image to a user using Firebase realtime database and React

查看:39
本文介绍了使用Firebase实时数据库和React将图像上传给用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将图像上传到数据库中的用户而不是存储中.我目前正在建立注册,并允许将图像添加到配置文件并将这些图像存储在您的UID中.当前,所有数据都会保存,需要图像或图像URL.是否有关于如何处理的想法,或者这是否是解决此问题的正确方法?

Is it possible to upload image to a user in your database and not storage. I am currently building out a registration and allowing the ability to add images to a profile and store those images in your UID. Currently all the data saves, expect the image or image url. Any thoughts of how to approach or if this is the correct way to go about this?

我在数据库中的JSON方案:

My JSON scheme in my database:

    {
  "users" : {
    "3pwcQ0VuzogVmmQ97yDExkMac1m1" : {
      "Email" : "greg@gmail.com",
      "code" : "bob",
      "image" : "",
      "location" : "fl"
    }
  }
}

反应JS:

    state = {
    email: '',
    password: '',
    code: 'bob',
    location: 'fl',
    image: null,
    url: '',
    error: null,
  };


  handleInputChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

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

  handleSubmit = (event) => {
    event.preventDefault();
    const { email, password, image } = this.state;
    const uploadTask = storage.ref(`images/${image.name}`).put(image);

    uploadTask.on('state_changed', () => {
      // complete function ....
      storage.ref('images').child(image.name).getDownloadURL().then(url => {
          console.log(url);
          this.setState({url});
      })
    });

    firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then((user) => {
        firebase
        .database()
        .ref('users/' + user.user.uid)
        .set({
          Email: user.user.email,
          code:  this.state.code,
          location:  this.state.location,
          image:  this.state.url
        })
        this.props.history.push('/');
      })
      .catch((error) => {
        this.setState({ error: error });
      });
  };

推荐答案

我认为您应该使用Firebase存储.这样,您将能够存储实际图像.

I think you should use firebase storage. That way you will be able to store the actual image.

检查此链接: https://firebase.google.com/docs/storage/

这篇关于使用Firebase实时数据库和React将图像上传给用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆