我在使用 Web 版本 9 将图像上传到 Firebase 时遇到问题。
我正在关注他正在其中构建 Facebook 克隆的平台之一的教程。我被困在 firebase 上传图像和文件的这一部分......
我检查了 firebase 的文档,并尝试找出应该更改的内容,但我无法做到。
我想要的是将 firebase 代码从旧版本转换为最新的 web V9。
这是我的代码,但在以前的版本中:
import { useSession } from 'next-auth/client';
import { useRef, useState } from 'react';
import { db, storage } from '../firebase';
import firebase from 'firebase';
function InputBox() {
const [session] = useSession();
const inputRef = useRef(null);
const filepickerRef = useRef(null);
const[imageToPost, setImageToPost] = useState(null);
const sendPost = (e) => {
e.preventDefault();
if (!inputRef.current.value) return;
db.collection('posts').add({
message: inputRef.current.value,
name: session.user.name,
email: session.user.email,
image: session.user.image,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
}).then(doc => {
if (imageToPost) {
const uploadTask = storage.ref(`posts/${doc.id}`).putString(imageToPost, 'data_url')
removeImage();
uploadTask.on('state_change', null, error => console.error(error),
() => {
//When the upload completes
storage.ref(`posts`).child(doc.id).getDownloadURL().then(url => {
db.collection('posts').doc(doc.id).set({
postImage: url
},
{ merge: true}
);
});
});
}
});
inputRef.current.value = "";
};
const addImageToPost = (e) => {
const reader = new FileReader();
if (e.target.files[0]) {
reader.readAsDataURL(e.target.files[0]);
}
reader.onload = (readerEvent) => {
setImageToPost(readerEvent.target.result);
};
};
const removeImage = () => {
setImageToPost(null);
};
return (here is my jsx)
如果你的 firebaseConfig 没问题,那么这应该可以工作!
import { setDoc, doc } from "firebase/firestore";
import { ref, uploadString, getDownloadURL, getStorage } from "firebase/storage";
if (imageToPost) {
const storage = getStorage();
const storageRef = ref(storage, `posts/${docum.id}`);
const uploadTask = uploadString(storageRef, imageToPost, 'data_url');
uploadTask.on('state_changed', null,
(error) => {
alert(error);
},
() => {
getDownloadURL(uploadTask.snapshot.ref)
.then((URL) => {
setDoc(doc(db, "posts", docum.id), { postImage:URL }, { merge: true});
});
}
)
removeImage();
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)