0

I am new to learning to react js with firebase storage. I am trying to upload multiple images in firebase v9. I have successfully done uploading a single image but am not able to do multiple images. I have watched tutorials but those are not updated.

Also after uploading all the images I want all the URLs in an array because I need to send it also in the backend.

 const [progress, setProgress] = useState(0);
 const [selectedImages, setSelectedImages] = useState([]);

    const onSelectFileUpload = (e) => {
        e.preventDefault();
        const file = e.target[0].files[0];
        uploadFiles(file);

    };

    const uploadFiles = (file) => {
        //
        if (!file) return;
        const sotrageRef = ref(storage, `files/${file.name}`);
        const uploadTask = uploadBytesResumable(sotrageRef, file);

        uploadTask.on(
            "state_changed",
            (snapshot) => {
                const prog = Math.round(
                    (snapshot.bytesTransferred / snapshot.totalBytes) * 100
                );
                setProgress(prog);
            },
            (error) => console.log(error),
            () => {
                getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
                    console.log("File available at", downloadURL);
                });
            }
        );
    };

HTML code:

    <form onSubmit={onSelectFileUpload}>
            <div className="shadow sm:rounded-md sm:overflow-hidden bg-white px-4 py-5 bg-white space-y-6 sm:p-6">

                <input
                    type="file"
                    name="images"
                    multiple
                    accept="image/png , image/jpeg, image/webp"
                />

                <div className=" py-3 text-right ">
                    <button type="submit" className="inline-flex justify-center py-2 px-4 border border-transparent drop-shadow-md text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Publish</button>
                </div>
            </div>
        </form>

Can anyone guide me on how can I solve it?

2 Answers 2

3
import { getDownloadURL, ref, uploadBytes } from "firebase/storage";
import { storage } from "../../firebase";


async function uploadImage(image) {
  const storageRef = ref(storage, `/posts/${Date.now()}-${image.name}`);

  const response = await uploadBytes(storageRef, image);
  const url = await getDownloadURL(response.ref);
  return url;
}

export default async function uploadImages(images) {
  const imagePromises = Array.from(images, (image) => uploadImage(image));

  const imageRes = await Promise.all(imagePromises);
  return imageRes; // list of url like ["https://..", ...]
}
Sign up to request clarification or add additional context in comments.

Comments

2

Solved


   const uploadFiles = (files) => {
        const promises = []
        files.map((file) => {
            console.log('loop');

            const sotrageRef = ref(storage, `files/${file.name}`);

            const uploadTask = uploadBytesResumable(sotrageRef, file);
            promises.push(uploadTask)
            uploadTask.on(
                "state_changed",
                (snapshot) => {
                    const prog = Math.round(
                        (snapshot.bytesTransferred / snapshot.totalBytes) * 100
                    );
                    setProgress(prog);
                },
                (error) => console.log(error),
                async () => {
                    await getDownloadURL(uploadTask.snapshot.ref).then((downloadURLs) => {
                        setURLs(prevState => [...prevState, downloadURLs])
                        console.log("File available at", downloadURLs);
                    });
                }
            );


        })
        Promise.all(promises)
            .then(() => alert('All images uploaded'))
            .then(err => console.log(err))

    };

    console.log(selectedImages);
    console.log(URLs);
    const handleSubmit = () => { uploadFiles(images); }

2 Comments

Can you please explain in more details how you solved the problem?
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.