firebase upload file
const [imagetoPost, setImagetoPost] = useState(null);
const sendPost = (e) => {
e.preventDefault();
if (!post) return null;
db.collection('posts')
.add({
// whatever you want to add other than file
})
.then((doc) => {
if (imagetoPost) {
// upload stuff
const uploadTask = storage
.ref(`posts/${doc.id}`)
.putString(imagetoPost, 'data_url');
// OPTIONAL: here you can remove the file from state
uploadTask.on(
'state_change',
null,
(error) => console.error(error),
() => {
// when the upload completes
storage
.ref(`posts/${doc.id}`)
.getDownloadURL()
.then((url) => {
db.collection('posts').doc(doc.id).set(
{ postImage: url },
{ merge: true }
);
});
}
);
}
});
};
const addPostImage = (e) => {
const reader = new FileReader();
if (e.target.files[0]) {
reader.readAsDataURL(e.target.files[0]);
}
reader.onload = (readerEvent) => {
setImagetoPost(readerEvent.target.result);
};
};