简体   繁体   English

使用 React 将图像上传到 firestore

[英]upload images to firestore using react

Im trying to upload an image to Firestore using react.我正在尝试使用 React 将图像上传到 Firestore。 I read the firebase documentation but I had some problems.我阅读了 firebase 文档,但遇到了一些问题。

here is the code:这是代码:

initialize a state:初始化一个 state:

const [image, setImage] = useState([]);

I'm getting the image like this:我得到这样的图像:

<input type="file" id="image" accept="image/*"className="hidden" onChange={(e) => onChangeImage(e)}/>

and storing it in a state like this:并将其存储在 state 中,如下所示:

const onChangeImage = (e) => {
    setImage([...image, e.target.files[0]]);
    console.log(e.target.files);
  };

and I'm using useEffect so when the state changes it logs to the console:我正在使用 useEffect,所以当 state 更改时,它会记录到控制台:

useEffect(() => {
    console.log("picture: ", image);
  }, [image]);

here is what it's logging:这是它正在记录的内容:

lastModified: 1664394000377
lastModifiedDate: Wed Sep 28 2022 22:40:00 GMT+0300 (Eastern European Summer Time) {}
name: "landscape.jpg"
size: 112285
type: "image/jpeg"
webkitRelativePath: ""
[[Prototype]]: File

in the firebase documentation, it says to create a ref for the image and a ref for the full path and I can't seem to find a way to get the full path of the image.在 firebase 文档中,它说要为图像创建一个 ref 并为完整路径创建一个 ref,但我似乎找不到获取图像完整路径的方法。

so is there a way I can get the full path or any other way to upload an image into firestore?那么有没有办法获得完整路径或任何其他方式将图像上传到 firestore?

Here is the function to upload image.这里是function上传图片。 you decide where to call it.您决定在哪里调用它。

// set initial state for the object 
const [data, setData] = useState(initialState);
// call setfile on file input onChange
const [file, setFile] = useState(null);


import { getDownloadURL, uploadBytesResumable, ref } from "firebase/storage";
import { storage } from "../firebase";
const uploadFile = () => {
  //By creating a reference to a file, your app gains access to it.
  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");
      switch (snapshot.state) {
        case "paused":
          console.log("Upload paused");
          break;
        case "running":
          console.log("Upload running");
          break;
        default:
          break;
      }
    },
    (error) => {
      console.log(error);
    },
    () => {
      getDownloadURL(uploadTask.snapshot.ref).then((downloadedURL) => {
        // you keep uploaded img url
        setData((prev) => ({ ...prev, img: downloadedURL }));
      });
    }
  );
};

you uploaded file and then in getDownloadURL function you store the uploaded img url in a state, so you can use it.您上传了文件,然后在getDownloadURL function 中将上传的 img url 存储在 state 中,因此您可以使用它。

prepare for the storage that you need above准备上面你需要的存储

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

const firebaseConfig = {
  apiKey: "************",
  authDomain: "************",
  projectId: "************",
  storageBucket: "************",
  messagingSenderId: "************",
  appId: "************",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const storage = getStorage(app);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM