我不知道为什么单击发送按钮时没有上传图像

问题描述 投票:0回答:0

我已经尝试了一切,但对我来说我的代码似乎没问题。我仍然不知道为什么当我点击发送按钮时我的图片没有上传到 firebase 实时数据库。

在我点击发送按钮后,如果我没有上传任何图像文件只是写了一个文本,它正在保存到 firebase 并且工作正常。但不知何故,当我尝试使用 msg 上传任何图像时,它不起作用。没有上传图片,只有文字正在保存。

输入.js

import React, { useContext, useState, useEffect } from 'react'
import image from '../assets/image.png'
import attachment from '../assets/attachment.png'
import { ChatContext } from '../context/ChatContext'
import { database, auth, storage } from '../firebase'
import { serverTimestamp, set, child, ref, update } from 'firebase/database'
import { ref as sRef, push } from "firebase/database";
import { getDownloadURL, uploadBytesResumable } from 'firebase/storage'


function Input() {

  const [text, setText] = useState("")
  const [img, setImg] = useState(null)

  const data = useContext(ChatContext)
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      setCurrentUser(user);
    });
    return () => unsubscribe();
  }, []);


  const handleSend = async () => {
    console.log(img, text, currentUser.uid);
    if (img === null && text && data.chatId!= null) {
     let userObj = Object.entries(data)[0];
     let chatIdObj = Object.entries(userObj[1]);
     let chatId = chatIdObj[1][1]; 
     const messagesRef = sRef(database, `chat/${chatId}/message`);
     const newMessageRef = push(messagesRef);
  
     const newMessage = {
        id: newMessageRef.key,
        text: text,
        senderID: currentUser?.uid,
        date: serverTimestamp(),
      };
      set(newMessageRef, newMessage);
      update(child(ref(database), `chats/${currentUser.uid}`), {
        [chatId+'/lastMessage']: {
          text: text
        },
        [chatId+'/date']: serverTimestamp(),
      })
    } 
    if (img!= null && data.chatId!= null) {
      console.log(img, text, currentUser.uid);
      let userObj = Object.entries(data)[0];
      let chatIdObj = Object.entries(userObj[1]);
      let chatId = chatIdObj[1][1];

      try {
        const storageRef = ref(storage, + `chat_Images`);
        const uploadTask = uploadBytesResumable(storageRef, img.name);
        uploadTask.on("error", (error) => {
          console.log("Error uploading image:", error);
         },() => {
           getDownloadURL(storageRef).then(async (downloadURL) => {
            console.log(downloadURL)
            const messagesRef = sRef(database, `chat/${chatId}/message`);
            const newMessageRef = push(messagesRef);
            const newMessage = {
              id: newMessageRef.key,
              text: text,
              image: downloadURL,
              senderID: currentUser?.uid,
              date: serverTimestamp(),
            };
            set(newMessageRef, newMessage);
            update(child(ref(database), `chats/${currentUser.uid}`), {
              [chatId+'/lastMessage']: {
                text: text
              },
              [chatId+'/date']: serverTimestamp(),
            });
           })
        })
      } 
      catch(err) {
        console.log(`line 68`, err.message)
      }
    }
  
    setText("")
    setImg(null)
  };
  
  return (
    <div className="input">
      <input
        type="text"
        placeholder='Type here...'
        onChange={(e) => setText(e.target.value)}
        value={text}
      />
      <div className="send">
        <img src={attachment} />
        
        <label htmlFor="msg-file">
          <img src={image} />
        </label>
        <input
          type="file"
          id="msg-file"
            
          onChange={(e) => setImg(e.target.files[0])}
          defaultValue={img || ''}
        />
        <button className='send-btn'
          onClick={handleSend}
        >Send</button>
      </div>
    </div>
  )
}

export default Input;
reactjs firebase-realtime-database firebase-storage
© www.soinside.com 2019 - 2024. All rights reserved.