Search code examples
javascriptfirebasefirebase-realtime-databasefirebase-storageasyncfileupload

Firebase upload with JavaScript fails


I am using js for the first time and i am clueless why my code isnt working. Maybe someone can help me with that:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/uikit.css">
        <link rel="stylesheet" href="css/styles.css">
        <script src="js/uikit.js"></script>
        <script src="js/uikit-icons.js"></script>

        <title>Face Recognition</title>
    </head>

    <body>


        <section>
            <a href="index.html">Back to home</a>
        </section>
        <input type="text" id="label" placeholder="Input name"/></br>
        <input type="file" id="photo"/></br>
        <button id="upload" onclick="uploadImage()"</button>

        <script type="module">
            import { initializeApp } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-app.js";
            import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-database.js";
            import { getStorage, ref as refStorage, uploadBytes, getDownloadURL } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-storage.js";

            const firebaseConfig = {
                my firebase config...;
            };
          
            const app = initializeApp(firebaseConfig);
            const db = getDatabase(app);
            const storage = getStorage(app);

            async function uploadImage(){
                const file = document.getElementById('photo').files[0];
                const label = document.getElementById('label').value;
                const storageRef = refStorage(storage, 'images/' + file.name);
                await uploadBytes(storageRef, file).then(async (snapshot) => {
                    console.log('File uploaded');
                    const downloadURL = await getDownloadURL(storageRef);
                    console.log('File at', downloadURL);
                    const dbRef = ref(db, 'images/' + label);
                    set(dbRef, {
                        name: label,
                        url: downloadURL
                    });
                });
            }
          </script>
    </body>
</html>

I tried different approaches but i cant get i done on my own. I succeded in uploading the image to the storage before, but then i wasnt able to save the url to the img and the label in the real-time database.

This is the error in the browser console:

project.html:59 Uncaught ReferenceError: uploadImage is not defined
at HTMLButtonElement.onclick (project.html:59:146)


Solution

  • You can try this code:

    <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-app.js";
    import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-database.js";
    import { getStorage, ref as refStorage, uploadBytes, getDownloadURL } from "https://www.gstatic.com/firebasejs/10.9.0/firebase-storage.js";
    
    const firebaseConfig = {
        // Your Firebase config
    };
    
    const app = initializeApp(firebaseConfig);
    const db = getDatabase(app);
    const storage = getStorage(app);
    
    async function uploadImage(){
        const file = document.getElementById('photo').files[0];
        const label = document.getElementById('label').value;
        const storageRef = refStorage(storage, 'images/' + file.name);
        await uploadBytes(storageRef, file).then(async (snapshot) => {
            console.log('File uploaded');
            const downloadURL = await getDownloadURL(storageRef);
            console.log('File at', downloadURL);
            const dbRef = ref(db, 'images/' + label);
            set(dbRef, {
                name: label,
                url: downloadURL
            });
        });
    }
    
    // Attach the function to the window object
    window.uploadImage = uploadImage;
    

    Additionaly, please make sure that your button tag is correctly closed like:

    <button id="upload" onclick="uploadImage()">Upload</button>