Tutorial Upload File ke Firebase Cloud Storage

Tutorial Upload File ke Firebase Cloud Storage. Kali ini kita akan membuat aplikasi berbasis web untuk mengupload gambar ke Firebase Cloud Storage. Kita akan menggunakan file yang sama dengan artikel sebelumnya https://tukangaplikasi.com/blog/login-dan-registrasi-dengan-firebase-authentication-pada-aplikasi-website/.

Pertama yang harus dilakukan adalah mengaktifkan module-nya dengan cara

  1. Buka https://console.firebase.google.com/u/0/
  2. Pilih Projek Firebase anda
  3. Klik Storage di sebelah kiri
  4. Lalu klik next saja

Jika sudah di aktifkan kita akan memulai

Tutorial Upload File ke Firebase Cloud Storage

Buka halaman register.html. Kita akan menambahkan 1 field baru yaitu field file

<div class="form-group">
  <label for="phone">Profile image</label>
  <input id="image" type="file" class="form-control-file" name="image" required>
  <div class="invalid-feedback">
    Image is required
  </div>
</div>

kemudian, kita akan memanggil file javascript

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

pastikan anda meletekannya di bawah

<script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-app.js"></script>

Kita akan mengubah fungsi signUp() di app.js. Kita akan mengambil file dari form nya seperti ini

var file = document.getElementById("image").files[0];
var imageUrl = "";

setelah itu kita akan memulai mengupload dan mengambil link file uploadnya lalu menyimpannya ke dalam firestore

var storageRef = firebase.storage().ref("img");
       var thisRef = storageRef.child(file.name);
       thisRef.put(file).then(function(snapshot) {
           snapshot.ref.getDownloadURL().then(function(downloadURL) {
               imageUrl= downloadURL;
             });
       }).catch(function(error){
           user.delete().then(function() {
               console.log("user deleted");
             }).catch(function(error) {
               console.log("failed delete user");
             });
       });

Kita akan menyesuaikan bagian saat menyinpan data ke firestore. Menjadi seperti ini

var db = firebase.firestore();
        db.collection("users").doc(uid).set({
            name: userFullName,
            email: userEmail,
            phone: userPhone,
            active:0,
            imageUrl:imageUrl,
            imageFileName:file.name
        }).then(function() {
            Swal.fire({icon: 'success', title: 'Success' ,text:'your account was created successfully, you can log in now.'}).then((value) => {
                setTimeout(function(){
                    window.location.replace("./dashboard.html");
                }, 1000)
            });         
        })
        .catch(function(error) {
           console.error("Error writing doc", error);
        });



Jadi fungsi signUp akan berubah menjadi seperti ini

function signUp(){
    var userFullName = document.getElementById("name").value;
    var userPhone = document.getElementById("phone").value;
    var userEmail = document.getElementById("email").value;
    var userPassword = document.getElementById("password").value;
    var file = document.getElementById("image").files[0];
    var imageUrl = "";
    firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((rslt) => {
        var user = firebase.auth().currentUser;
        var uid;
        if (user != null) {
            uid = user.uid;
        }
        var storageRef = firebase.storage().ref("img");
        var thisRef = storageRef.child(file.name);
        thisRef.put(file).then(function(snapshot) {
            snapshot.ref.getDownloadURL().then(function(downloadURL) {
                imageUrl= downloadURL;
                var db = firebase.firestore();
                db.collection("users").doc(uid).set({
                    name: userFullName,
                    email: userEmail,
                    phone: userPhone,
                    active:0,
                    imageUrl:imageUrl
                }).then(function() {
                    Swal.fire({icon: 'success', title: 'Success' ,text:'your account was created successfully, you can log in now.'}).then((value) => {
                        setTimeout(function(){
                            window.location.replace("./dashboard.html");
                        }, 1000)
                    });         
                })
                .catch(function(error) {
                console.error("Error writing doc", error);
                });
              });
        }).catch(function(error){
            user.delete().then(function() {
                console.log("user deleted");
              }).catch(function(error) {
                console.log("failed delete user");
              });
        });
        
    }).catch((error) => {
        Swal.fire({icon: 'error',
        title: 'Oops...',text:error.message});
    });
}

kemudian pada file dashboard.html kita akan melakukan perubahan saat kita membaca data dari firestore mejadi seperti ini

async function getDoc(id) {
      const snapshot = await db.collection('users').doc(id).get();
      const data = snapshot.data();
      $("#usersection").html("<img src='"+data['imageUrl']+"'"+
                  "<p>"+data['name']+"</p>" + 
                  "<p>"+data['email']+"</p>" + 
                  "<p>"+data['phone']+"</p>");
    }

Nah ketika kita upload file baru dengan melalui form edit kita. Kita akan menghapus file yg lama terlebih dahulu, ubah form edit nya menjadi

<form method="POST" class="my-login-validation" id="updateForm" novalidate="">
                <input type="hidden" id="oldFile">
                <div class="form-group">
                  <label for="phone">Image</label>
                  <input id="image" type="file" class="form-control-file" name="image">
                
                </div>

                <div class="form-group">
                  <label for="name">Name</label>
                  <input id="name" type="text" class="form-control" name="name" required autofocus>
                  <div class="invalid-feedback">
                    What's your name?
                  </div>
                </div>

                <div class="form-group">
                  <label for="phone">Phone</label>
                  <input id="phone" type="text" class="form-control" name="phone" required data-eye>
                  <div class="invalid-feedback">
                    Phone is required
                  </div>
                </div>

                <div class="form-group m-0">
                  <button type="submit" class="btn btn-primary btn-block">
                    Update
                  </button>
                </div>
              </form>

lalu, ubah fungsi getDoc menjadi

async function getDoc(id) {
          const snapshot = await db.collection('users').doc(id).get();
          const data = snapshot.data();         
            $("#name").val(data['name']);
      $("#phone").val(data['phone']);
      $("#oldFile").val(data['imageFileName']);
      }

nah jadi kita akan mengambil nama file saat ini yang ada di firestore lalu kita taruh di hidden field. Kita juga perlu melakukan filter, apakah ada gambar baru atau tidak, jika tidak kita tidak akan menghapus gambar sebelumnya. Ubah fungsi updateData() menjadi

function updateData(){
    var phone = document.getElementById("phone").value;
    var name = document.getElementById("name").value;
    var oldFile = document.getElementById("oldFile").value;

    var file = document.getElementById("image").files[0];
    var imageUrl = "";
    if(file != null){
        //Jika upload gambar baru
        console.log(oldFile);
        var storageRef = firebase.storage().ref("img/");
        var desertRef = storageRef.child(oldFile);
        desertRef.delete();
        var storageRef = firebase.storage().ref("img/");
        var thisRef = storageRef.child(file.name);
        thisRef.put(file).then(function(snapshot) {
            snapshot.ref.getDownloadURL().then(function(downloadURL) {
                imageUrl= downloadURL;
                var db = firebase.firestore();
                firebase.auth().onAuthStateChanged(function(user) {
                db.collection("users").doc(user.uid).update({imageFileName:file.name,name: name , phone:phone , imageUrl:imageUrl}).then((result) => {
                    Swal.fire({icon: 'success', title: 'Success' ,text:'Update data success'}).then((value) => {
                        window.location.replace("./dashboard.html");
                    });
                });
            });
              });
        }).catch(function(error){
            user.delete().then(function() {
                console.log("user deleted");
              }).catch(function(error) {
                console.log("failed delete user");
              });
        });
    }else{
        firebase.auth().onAuthStateChanged(function(user) {
            db.collection("users").doc(user.uid).update({name: name , phone:phone}).then((result) => {
                Swal.fire({icon: 'success', title: 'Success' ,text:'Update data success'}).then((value) => {
                    window.location.replace("./dashboard.html");
                });
            });
        });
    }

    
}

Sekian artikel kali ini, semoga bermanfaat. Link demo firebaseauth.tukangaplikasi.com

Tinggalkan Balasan

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Kami memberikan tutorial baru tiap harinya !!!

You have Successfully Subscribed!

%d blogger menyukai ini: