使用 React 将图片上传到 Firebase 存储时出现问题

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

我在尝试上传 profpic 时不断收到此警报:“FirebaseError: Firebase Storage: User does not have permission to access 'files/hhh.png'. (storage/unauthorized)”

ChatGpt 建议更改 Firebase 存储规则,以允许所有用户(无论是否经过身份验证)访问文件并对其进行读/写。出于安全原因,我宁愿不这样做。有什么办法可以更改我的代码以避免这样做吗?

这是我的 firebase 文件:

    import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import { getStorage } from "firebase/storage";

const firebaseConfig = {
   
  };

  const firebaseApp = firebase.initializeApp(firebaseConfig);
  const db = firebaseApp.firestore();
  const auth = firebase.auth();
  export const storage = getStorage(firebaseApp);

  export {db, auth};

这是我的登录组件:

import React, { useState } from "react";
import { auth } from "./firebase";
import { useDispatch } from "react-redux";
import { login } from "./features/userSlice";
import hpic from "./images/screenshot.png";

import { storage } from './firebase';
import { ref, getDownloadURL, uploadBytesResumable } from "firebase/storage";

function Login() {
  
  const [progresspercent, setProgresspercent] = useState(0);
  const [name, setName] = useState("");
  const [profpic, setProfpic] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const dispatch = useDispatch();

  

  const loginToApp = (e) => {
    e.preventDefault();
    const file = e.target[1]?.files[0]

    if (!file) return;

    const storageRef = ref(storage, `files/${file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, file);

    uploadTask.on("state_changed",
      (snapshot) => {
        const progress =
          Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
        setProgresspercent(progress);
      },
      (error) => {
        alert(error);
      },
      () => {
        getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
          setProfpic(downloadURL)
        });
      }
    );

    auth
      .signInWithEmailAndPassword(email, password)
      .then((userAuth) => {
        dispatch(
          login({
            email: userAuth.user.email,
            uid: userAuth.user.uid,
            displayName: userAuth.user.displayName,
            photoUrl: userAuth.user.photoURL,
          })
        );
      })
      .catch((error) => alert(error));
  };

  const register = () => {
    if (!name) {
      return alert("Please enter your name!");
    }
  
    const storageRef = ref(storage, `files/${profpic.name}`);
    const uploadTask = uploadBytesResumable(storageRef, profpic);
  
    uploadTask.on("state_changed",
      (snapshot) => {
        const progress =
          Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
        setProgresspercent(progress);
      },
      (error) => {
        alert(error);
      },
      () => {
        getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
          auth
            .createUserWithEmailAndPassword(email, password)
            .then((userAuth) => {
              userAuth.user
                .updateProfile({
                  displayName: name,
                  photoUrl: downloadURL,
                })
                .then(() => {
                  dispatch(
                    login({
                      email: userAuth.user.email,
                      uid: userAuth.user.uid,
                      displayName: name,
                      photoUrl: downloadURL,
                    })
                  );
                });
            })
            .catch((error) => alert(error));
        });
      }
    );
  };
  

  return (
    <div className="grid grid-cols-1  bg-cover bg-center bg-fixed bg-opacity-80 bg-gradient-to-r from-blue-100 to-green-100 md:grid-cols-2 gap-8 mx-auto py-20 px-6 md:px-32 items-center">
      <form className="flex flex-col items-center w-full">
        

        <input
          className="w-[60%]  h-12 px-3 rounded mb-3"
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Full name (required if registering)"
        />
        <input
          className="w-[60%] h-12 px-3 rounded mb-3 "
          type="file"
          onChange={(event) => {
            setProfpic(event.target.files[0]);
          }}
          placeholder="Optional Profile Pic (Paste URL Here)"
        />
        
        <input
          className="w-[60%]  h-12 px-3 rounded mb-3  "
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Email"
        />
        <input
          className="w-[60%]  h-12 px-3 rounded mb-3  "
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Password"
        />
        <button
          className="w-[60%]  h-12 bg-green-500 rounded text-white font-bold mb-3 hover:bg-green-500 transition-all duration-200 hover:shadow-xl"
          type="submit"
          onClick={loginToApp}
        >
          Sign In
        </button>
        <p className="bg-white rounded p-2 text-center transition-all duration-200">
          Not a member? Fill out the information above and Click:
          <span
            className="text-blue-500 hover:text-blue-900 pl-2 font-bold cursor-pointer"
            onClick={register}
          >
            Register Now
          </span>
        </p>
      </form>
      <div className="hidden md:block">
        <img
          className="w-full h-auto rounded-lg  border-2 border-gray-400 object-cover"
          src={hpic}
          alt="login pic"
        />
      </div>
    </div>
  );
}

export default Login
reactjs firebase firebase-storage
© www.soinside.com 2019 - 2024. All rights reserved.