将IMG上传到firebase存储+创建新的水桶

发布于 2025-01-29 16:43:09 字数 2292 浏览 1 评论 0原文

自学成才的编码器。希望我能正确解释这一点。我正在尝试创建一个食谱网站,用户可以在其中使用图像上传自己的自定义食谱。用户提交表单,信息将上传到数据库集合“指南”。将文件上传到firebase存储如何将URL发送回反应,以便表单可以将URL记录到步骤数组中?

这是用户在上传组件中上传IMG以上载IMG上传的逻辑:

    const uploadFile = () => {
      const name = new Date().getTime() + file.name
      const storageRef = ref(storage, file.name)

      const uploadTask = uploadBytesResumable(storageRef, file);

uploadTask.on('state_changed', 
  (snapshot) => {
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    setPercentage(progress)
    switch (snapshot.state) {
      case 'paused':
        console.log('Upload is paused');
        break;
      case 'running':
        console.log('Upload is running');
        break;
        default: 
          break;
    }
  }, 
  (error) => {
    console.log(error)
  }, 
  () => {
    // Handle successful uploads on complete
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
      setData((prev) => ({...prev, img: downloadURL}))
    });
  }
);

    }
    file && uploadFile();
  }, [file]);



这是在上传组件中也可以上传/提交表单的逻辑。


  const handleAddGuide = async (e) => {
    e.preventDefault();
    const newId = uuidv4()

    await setDoc(doc(db, "guides", newId), {
      author: e.target.author.value,
      categoryId: "100",
      categoryName: e.target.categoryName.value,
      // coverImg: imgURL,
      id: newId,
      name: e.target.name.value,
      tags: e.target.tags.value,
      steps: [
        {
          step: e.target.step.value,
          img: file.url <---- I need this file to upload to a folder inside storage named dynamically after the name of the recipe ("e.target.name.value").
        }
      ]
    });
  };

这是我初始化DB和存储的地方:


firebase.js 

import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore'
import { getAuth } from "firebase/auth";
import "firebase/storage"
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  <details> 
}

const app = initializeApp(firebaseConfig);
export const userAuth = getAuth()
export const db = getFirestore(app)
export const storage = getStorage(app);

Self taught coder here. Hopefully I can explain this properly. I'm trying to create a recipe website where a user can upload their own custom recipe with images. The user submits a form and the info uploads to a database collection 'guides'. How does the file being uploaded to firebase storage send back a URL to react so that the form can record the URL into the steps array?

This is the logic for user to upload img in the form, inside Upload component:

    const uploadFile = () => {
      const name = new Date().getTime() + file.name
      const storageRef = ref(storage, file.name)

      const uploadTask = uploadBytesResumable(storageRef, file);

uploadTask.on('state_changed', 
  (snapshot) => {
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    setPercentage(progress)
    switch (snapshot.state) {
      case 'paused':
        console.log('Upload is paused');
        break;
      case 'running':
        console.log('Upload is running');
        break;
        default: 
          break;
    }
  }, 
  (error) => {
    console.log(error)
  }, 
  () => {
    // Handle successful uploads on complete
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
      setData((prev) => ({...prev, img: downloadURL}))
    });
  }
);

    }
    file && uploadFile();
  }, [file]);



Here is the logic to upload/submit form also inside the Upload component.


  const handleAddGuide = async (e) => {
    e.preventDefault();
    const newId = uuidv4()

    await setDoc(doc(db, "guides", newId), {
      author: e.target.author.value,
      categoryId: "100",
      categoryName: e.target.categoryName.value,
      // coverImg: imgURL,
      id: newId,
      name: e.target.name.value,
      tags: e.target.tags.value,
      steps: [
        {
          step: e.target.step.value,
          img: file.url <---- I need this file to upload to a folder inside storage named dynamically after the name of the recipe ("e.target.name.value").
        }
      ]
    });
  };

And this is where I initialize db and storage:


firebase.js 

import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore'
import { getAuth } from "firebase/auth";
import "firebase/storage"
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  <details> 
}

const app = initializeApp(firebaseConfig);
export const userAuth = getAuth()
export const db = getFirestore(app)
export const storage = getStorage(app);

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文