Home > Net >  How to upload images to Firebase web v9 using reactjs
How to upload images to Firebase web v9 using reactjs

Time:10-27

I am having an issue concerning uploading images to firebase but using web version 9. I am following along with a toturial on one of the platforms in which he is building a facebook clone. and I am stuck in this part of firebase uploading images and files... I checked the documentations of firebase and i tried to figure out to should be changed, but I couldn't do it. What I want is to convert the firebase code from the old version to the newest one web V9. This is my code but in the previous version:

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)

CodePudding user response:

if your firebaseConfig is okay, then this should work!

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();
            };

CodePudding user response:

Actually everything is detailed in the documentation.

To replace the uploadTask definition

const uploadTask = storage.ref(`posts/${doc.id}`).putString(imageToPost, 'data_url')

do

import { getStorage, ref, uploadString, getDownloadURL } from "firebase/storage";

const storage = getStorage();
const storageRef = ref(storage, `posts/${doc.id}`);

const message = 'This is my message.';
const uploadTask = uploadString(storageRef, imageToPost, 'data_url');

and to replace the upload monitoring block, do

import { doc, setDoc } from "firebase/firestore"; 

uploadTask.on('state_changed',
  null
  (error) => {
    // ...
  }, 
  () => {
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
       setDoc(doc(db, "posts", doc.id), { postImage: url }, { merge: true});
    });
  }
);

Note that the UploadTask object behaves like a Promise, and resolves with its snapshot data when the upload completes, so you can also do uploadTask.then() if you are just interested by the complete event.

  • Related