reactjs - 如何使用 reactjs 将图像上传到 Firebase web v9
问题描述
我在将图像上传到 firebase 但使用网络版本 9 时遇到问题。我正在关注他正在构建 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();
};
推荐阅读
- android - 使用一个 Android 应用处理两个不同的 Firebase 实时数据库
- php - 数据透视表上的 HasMany 使用了错误的 ID
- xamarin - Xamarin.Forms UWP 应用程序不能在 XBOX 上作为本机工作
- python-3.x - 如何删除字典的前几行?
- python - 在Python中定义类变量时如何引用类方法?
- javascript - javascript获取最新的属性值
- android - 如何在 google play 中保护我的 api 调用(通过身份验证)
- ios - UIView在设置宽度等于滚动视图时忽略我的约束?
- nginx - Nginx - 在特定路径中更改项目根目录
- javascript - 使用 Javascript ES6 递归地进行二分搜索