Firebase存储:操作' uploadbytes'

发布于 2025-02-03 17:59:58 字数 5448 浏览 1 评论 0原文

您好,我目前正在数据库中学习Firestore。我试图将数据从状态发送到数据库,但是我遇到错误,说无法在root上执行上传。我对firebase了解不多,所以我很难弄清楚这一点

firebaseError:firebase存储:无法在root引用上执行操作'uploadbytes',使用子女(例如.child('file.png')创建非root引用。 (存储/无效 - 根操作)

这是我的代码

const LoginCustomer: React.FC = () => {

    const [email, setEmail] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [showLoading, setShowLoading] = useState(false);
    const [present, dismiss] = useIonToast();
    const { login, signInWithGoogle } = useAuth();
    const history = useHistory();

    const mounted = useRef(false);

    const db = getFirestore();
    const [selectedFile, setSelectedFile] = useState<File>();
    const [fileName, setFileName] = useState('');
    const storage = getStorage();

    const imagesRef = ref(storage, 'images');

    const fileChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) =>{
        setSelectedFile(event.target!.files![0]);
        setFileName(event.target!.files![0].name);
    };

    const insertHandler = async() => {
        const storageRef = ref(storage, fileName);
        uploadBytes(storageRef, selectedFile as Blob).then(() => {
          console.log('upload file succes');
          getDownloadURL(ref(storage, fileName)).then((url)=>{
              addData(url);
          })
        })
      };

    useEffect(() => {
        mounted.current = true;
        return () => {
            mounted.current = false;
        }
    }, [])

    
        const addData = async(url: string) =>{
            try{
                const docRef = await addDoc(collection(db, "users"),{
                    email: email,
                    password: password,
                    foto: fileName,
                    fotoUrl: url
                });
                console.log("Document written with ID : ", docRef.id);
            } catch (e) {
                console.error("Error adding document: ", e);
            }
        }
  
    
  return (
    <IonPage>
      <IonContent className="body" class="ion-padding">
          <img className="logoLogin" src={logo} />
        <IonItem lines="none" className="backgroundItem"> 
            <IonText className='text1'>
                Pandawa Craft Store 
            </IonText>
        </IonItem>
        <IonItem lines="none" className='textItem'> 
            <IonText className='text2'>
               Login
            </IonText>
        </IonItem>
        <IonGrid className="gridinput1">
        <IonRow>
            <IonInput type='email' className="inputEmail" value={email} placeholder="Email" onIonChange={e => setEmail(e.detail.value!)}></IonInput>
        </IonRow>
        </IonGrid>

        <IonGrid className="gridinput2">
        <IonRow>
            <IonInput type='password' className="inputEmail" value={password} placeholder="Password" onIonChange={e => setPassword(e.detail.value!)}></IonInput>
        </IonRow>
        </IonGrid>
        <IonGrid className="gridinput1">
        <IonRow>
            <IonButton onClick={insertHandler} onSubmit={async e =>{
                e.preventDefault()
                if (!email || !password){
                    present({
                        buttons: [{ text: 'hide', handler: () => dismiss() }],
                        message: 'Credentials not valid',
                        onDidDismiss: () => console.log('dismissed'),
                        onWillDismiss: () => console.log('will dismiss'),
                      })
                } else {
                    setShowLoading(true)
                    setIsSubmitting(true)
                    login(email, password)
                    .then((response) => {
                        console.log(response)
                        history.push('/home')
                    })
                    .catch((error) => console.log(error.message)).finally(() => mounted.current && setIsSubmitting(false))
                }
            }}
             className="buttonLogin" expand="block" size="default" color="new">
                Login
            </IonButton>
            <IonLoading
                cssClass='my-custom-class'
                isOpen={showLoading}
                onDidDismiss={() => setShowLoading(false)}
                message={'Login...'}
                duration={500}
            />
        </IonRow>
        </IonGrid>
        
        <IonGrid>
            <p className="textDetail">Or Continue with </p>
        </IonGrid>
          
      <IonButton className="btnGoogle" onClick={()=> signInWithGoogle()
            .then(user => {
                console.log(user)
                history.push('/home')
                })
            .catch(error => console.log(error))}
            color="new"
            >
               Google Sign In
        </IonButton>
            <p className="textSignup"><a href="/registercustomer">New in pandawaCS ? Sign Up Now</a></p>
    </IonContent>   
    </IonPage>
  );
};

export default LoginCustomer;

(存储/无效

Hello im currently learning firestore from database. i tried to send the data from state to database, but i encounter error saying that uploadbytes cannot be performed on root. i dont know much about firebase so im having hard time trying to figuring this out

FirebaseError: Firebase Storage: The operation 'uploadBytes' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png'). (storage/invalid-root-operation)

this is my code

const LoginCustomer: React.FC = () => {

    const [email, setEmail] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [showLoading, setShowLoading] = useState(false);
    const [present, dismiss] = useIonToast();
    const { login, signInWithGoogle } = useAuth();
    const history = useHistory();

    const mounted = useRef(false);

    const db = getFirestore();
    const [selectedFile, setSelectedFile] = useState<File>();
    const [fileName, setFileName] = useState('');
    const storage = getStorage();

    const imagesRef = ref(storage, 'images');

    const fileChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) =>{
        setSelectedFile(event.target!.files![0]);
        setFileName(event.target!.files![0].name);
    };

    const insertHandler = async() => {
        const storageRef = ref(storage, fileName);
        uploadBytes(storageRef, selectedFile as Blob).then(() => {
          console.log('upload file succes');
          getDownloadURL(ref(storage, fileName)).then((url)=>{
              addData(url);
          })
        })
      };

    useEffect(() => {
        mounted.current = true;
        return () => {
            mounted.current = false;
        }
    }, [])

    
        const addData = async(url: string) =>{
            try{
                const docRef = await addDoc(collection(db, "users"),{
                    email: email,
                    password: password,
                    foto: fileName,
                    fotoUrl: url
                });
                console.log("Document written with ID : ", docRef.id);
            } catch (e) {
                console.error("Error adding document: ", e);
            }
        }
  
    
  return (
    <IonPage>
      <IonContent className="body" class="ion-padding">
          <img className="logoLogin" src={logo} />
        <IonItem lines="none" className="backgroundItem"> 
            <IonText className='text1'>
                Pandawa Craft Store 
            </IonText>
        </IonItem>
        <IonItem lines="none" className='textItem'> 
            <IonText className='text2'>
               Login
            </IonText>
        </IonItem>
        <IonGrid className="gridinput1">
        <IonRow>
            <IonInput type='email' className="inputEmail" value={email} placeholder="Email" onIonChange={e => setEmail(e.detail.value!)}></IonInput>
        </IonRow>
        </IonGrid>

        <IonGrid className="gridinput2">
        <IonRow>
            <IonInput type='password' className="inputEmail" value={password} placeholder="Password" onIonChange={e => setPassword(e.detail.value!)}></IonInput>
        </IonRow>
        </IonGrid>
        <IonGrid className="gridinput1">
        <IonRow>
            <IonButton onClick={insertHandler} onSubmit={async e =>{
                e.preventDefault()
                if (!email || !password){
                    present({
                        buttons: [{ text: 'hide', handler: () => dismiss() }],
                        message: 'Credentials not valid',
                        onDidDismiss: () => console.log('dismissed'),
                        onWillDismiss: () => console.log('will dismiss'),
                      })
                } else {
                    setShowLoading(true)
                    setIsSubmitting(true)
                    login(email, password)
                    .then((response) => {
                        console.log(response)
                        history.push('/home')
                    })
                    .catch((error) => console.log(error.message)).finally(() => mounted.current && setIsSubmitting(false))
                }
            }}
             className="buttonLogin" expand="block" size="default" color="new">
                Login
            </IonButton>
            <IonLoading
                cssClass='my-custom-class'
                isOpen={showLoading}
                onDidDismiss={() => setShowLoading(false)}
                message={'Login...'}
                duration={500}
            />
        </IonRow>
        </IonGrid>
        
        <IonGrid>
            <p className="textDetail">Or Continue with </p>
        </IonGrid>
          
      <IonButton className="btnGoogle" onClick={()=> signInWithGoogle()
            .then(user => {
                console.log(user)
                history.push('/home')
                })
            .catch(error => console.log(error))}
            color="new"
            >
               Google Sign In
        </IonButton>
            <p className="textSignup"><a href="/registercustomer">New in pandawaCS ? Sign Up Now</a></p>
    </IonContent>   
    </IonPage>
  );
};

export default LoginCustomer;

How do i solve this problem the data not going into my database

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

々眼睛长脚气 2025-02-10 17:59:58

尝试以下操作:

const storageref = ref(存储,userImages/$ {file.name});

Try this:

const storageRef = ref(storage, userImages/${file.name});

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文