0
votes

I am trying to upload an image from HTML form to firebase storage using an external JS file, but when I try to upload the image file (which is not empty - it exists) the path to the image location is not created on firebase storage when I execute the storageRef.put(image); function, and also the image itself (obviously) not being saved.

this is my code:

index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>אורט ביאליק עדכון פרטים</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
    <style>
        html, body {
            min-height: 100%;
            direction: rtl
        }

        body, div, form, input, select, p {
            padding: 0;
            margin: 0;
            outline: none;
            font-family: Roboto, Arial, sans-serif;
            font-size: 16px;
            color: #eee;
        }

    body { background: url("https://firebasestorage.googleapis.com/v0/b/XXXXXXXX.appspot.com/o/not%20to%20delete%2Fbackground.jpeg?alt=media&token=b5e0cc70-dc1c-40c7-a3fa-15694541828e") no-repeat center; background-size: cover; }

        h1, h2 {
            text-transform: uppercase;
            font-weight: 400;
        }

        h2 {
            margin: 0 0 0 8px;
        }

        .main-block {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100%;
            padding: 25px;
            background: rgba(0, 0, 0, 0.5);
        }

        .left-part, form {
            padding: 25px;
        }

        .left-part {
            text-align: center;
        }

        .fa-graduation-cap {
            font-size: 72px;
        }

        form {
            background: rgba(0, 0, 0, 0.7);
        }

        .title {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .info {
            display: flex;
            flex-direction: column;
        }

        input, select {
            padding: 5px;
            margin-bottom: 30px;
            background: transparent;
            border: none;
            border-bottom: 1px solid #eee;
        }

            input::placeholder {
                color: #eee;
            }

        option:focus {
            border: none;
        }

        option {
            background: black;
            border: none;
        }

        .btn-item, button {
            padding: 10px 5px;
            margin-top: 20px;
            border-radius: 5px;
            border: none;
            background: #26a9e0;
            text-decoration: none;
            font-size: 15px;
            font-weight: 400;
            color: #fff;
        }

        .btn-item {
            display: inline-block;
            margin: 20px 5px 0;
        }

        button {
            width: 100%;
        }

            button:hover, .btn-item:hover {
                background: #85d6de;
            }

        @media (min-width: 568px) {
            html, body {
                height: 100%;
            }

            .main-block {
                flex-direction: row;
                height: calc(100% - 50px);
            }

            .left-part, form {
                flex: 1;
                height: auto;
            }
        }
    </style>
</head>
<body>
    <div class="main-block">
        <div class="left-part">
            <img src="https://firebasestorage.googleapis.com/v0/b/XXXXXXXXX.appspot.com/o/not%20to%20delete%2Fkiryat_bialik_img.jpg?alt=media&token=5d637243-1cb1-430c-a7c5-1a98329bb3a0">
        </div>

        <form name="RegForm" action="/">
            <div class="title">
                <i class="fas fa-pencil-alt"></i>
                <h2>מכללת אורט ביאליק - עדכון פרטים אישיים</h2>
            </div>
            <div class="info">
                <input class="fname" type="text" name="HEfname" id="HEfname" maxlength="20" required autofocus placeholder="שם פרטי">
                <input class="fname" type="text" name="HElname" id="HElname" maxlength="20" required placeholder="שם משפחה">
                <input class="fname" type="text" name="ENfname" id="ENfname" maxlength="20" required placeholder="שם פרטי באנגלית">
                <input class="fname" type="text" name="ENlname" id="ENlname" maxlength="20" required placeholder="שם משפחה באנגלית">
                <input type="text" name="Email" inputmode="email" id="email" required maxlength="40" placeholder="Email">
                <input type="text" name="id" id="id" required maxlength="9" placeholder="מספר תעודת זהות">
                <input type="file" name="img" id="img" required accept="image/*">
            </div>
            <button type="submit" name="submit" id="submit" value="submit" onclick="return validation();" href="/">שלח</button>
        </form>
    </div>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js"></script>

    <script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-storage.js"></script>

    <script src="js/formValidation.js"></script>
    <script src="js/formSubmission.js"></script>
</body>
</html>

formSubmission.js:



// My web app's Firebase configuration
var firebaseConfig = {
    apiKey: "XXXXXXXXXXXX",
    authDomain: "XXXXXXXXXXXX.firebaseapp.com",
    databaseURL: "https://XXXXXXXXXXXX.firebaseio.com",
    projectId: "XXXXXXXXXXXX",
    storageBucket: "XXXXXXXXXXXX.appspot.com",
    messagingSenderId: "XXXXXXXXXXXX",
    appId: "XXXXXXXXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Reference Users collection
var databaseRef = firebase.database().ref('Users');

// Listen for form submit
document.forms.RegForm.addEventListener('submit', submitForm);

// Submit form
function submitForm() {
    //if (validation()) {
    // Get values
    var HEfname = getInputVal('HEfname');
    var ENfname = getInputVal('ENfname');
    var HElname = getInputVal('HElname');
    var ENlname = getInputVal('ENlname');
    var email = getInputVal('email');
    var id1 = getInputVal('id');
    var imageFile = document.getElementById('img').files[0];

    //this VAR's are used in 'saveUser()'; function. ---NOT IN USE---
    // unused value=5;  if false value=0; if true value=1
    var isSavedDatabase = false; //  if user data successfully commited to Firebase Database.
    var isSavedImage = false; //  if user image successfully commited to Firebase Storage.

    // Save User
    saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile);

}
    // Function to get get form values
    function getInputVal(id) {
        return document.getElementById(id).value;
    }

    // Save User to firebase
function saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile) {

    // reference to image path in storage 'passportImages/id1' (id1 is current user ID)
    var imageRef = firebase.storage().ref().child('passportImages/' + id1);


    //save User to database
    var newUserRef = databaseRef.child(id1);
    newUserRef.set({
        HEfname: HEfname,
        HElname: HElname,
        ENfname: ENfname,
        ENlname: ENlname,
        email: email,
        id: id1
    }, function (error) {
        if (error) {
            // The write failed
            console.log("User info could not be saved: " + error);
        } else {
            // Data saved successfully!
            isSavedDatabase = true;
            console.log("User info saved successfully!");
            saveImage(imageFile, id1);


            //imageRef.delete(); // remove user image from storage if his info could not be saved t database.
        }
    });




    //save image to storage by ID
    function saveImage(imageFile, id) {
        // Upload file to the object 'passportImages/id1' (id1 is current user ID)
        var uploadTask = firebase.storage().ref().child('passportImages/' + id).put(imageFile);

        // Listen for state changes, errors, and completion of the upload.
        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
            function (snapshot) {
                // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
                var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                console.log('Upload is ' + progress + '% done');
                switch (snapshot.state) {
                    case firebase.storage.TaskState.PAUSED: // or 'paused'
                        console.log('Upload is paused');
                        break;
                    case firebase.storage.TaskState.RUNNING: // or 'running'
                        console.log('Upload is running');
                        break;
                }
            }, function (error) {
                databaseRef.child(id).remove(); //remove user info from database if his image could not be uploaded to storage too.
                console.log(error);
                window.alert("Something went wrong, please try again");

                // A full list of error codes is available at
                // https://firebase.google.com/docs/storage/web/handle-errors
                switch (error.code) {
                    case 'storage/unauthorized':
                        // User doesn't have permission to access the object
                        console.log("Image: User doesn't have permission to access the object");
                        break;

                    case 'storage/canceled':
                        // User canceled the upload
                        console.log("Image: User canceled the upload");
                        break;

                    case 'storage/unknown':
                        // Unknown error occurred, inspect error.serverResponse
                        console.log("Image: Unknown error occurred, inspect error.serverResponse");
                        break;
                }
            }, function () {
                // Upload completed successfully!
                isSavedImage = true;
                console.log("Image uploaded successfully!");
                finalCall();
            });
        //if all data commited successfully to Firebase pop a massage and reset form.
        function finalCall() {


            // Show alert
            window.alert("Your info has been sent!");



            // Clear form
            document.forms.RegForm.reset();
        }
    }
    //}
}
1

1 Answers

0
votes

It is probably because you assign the submit type to your button. Your form is probably submitted before the submitForm() method is triggered.

If this assumption is correct, changing the type to button, as follows, should do the trick:

<button type="button" id="submit" onclick="return validation();" href="/">שלח</button>

See the W3 specification for more detail.