Simples App Realtime 2020 parte 3

Upload de arquivos

Continuando a aplicação, nesse vídeo mostro como é simples fazer upload de arquivos para o Firebase Cloud Storage e como o processo disponibiliza informações sobre o andamento e ações de pausar, retomar e cancelar o envio.

#firebase

Código que foi construído até agora

<html>
  <head>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
      crossorigin="anonymous"
    />
    <!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-analytics.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-storage.js"></script>

    <script>
      // Your web app's Firebase configuration
      var firebaseConfig = {
        apiKey: '*************',
        authDomain: '*************',
        databaseURL: '*************',
        projectId: '*************',
        storageBucket: '*************',
        messagingSenderId: '*************',
        appId: '*************',
        measurementId: '*************',
      };
      // Initialize Firebase
      const app = firebase.initializeApp(firebaseConfig);
      const auth = firebase.auth();
      const db = firebase.database();
      const storageRef = firebase.storage().ref();
      //   firebase.analytics();
      // app.auth().signInAnonymously().then(user=>{

      //     // app.database().ref('informacoes').on('value',snapshot=>{
      //     //     console.log(snapshot.val())
      //     // } )
      // })
    </script>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        margin: 0%;
        padding: 0%;
      }
      .container {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .cara-de-dentro {
        width: 300px;
        height: 200px;
        display: flex;
        flex-direction: column;
      }
      input[type='file'] {
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="cara-de-dentro form-group">
        <div>
          <h3></h3>
        </div>
        <input
          type="text"
          class="form-control m-2"
          id="nome"
          placeholder="nome"
        />
        <input
          type="email"
          class="form-control m-2"
          id="email"
          placeholder="email"
        />
        <input
          type="password"
          class="form-control m-2"
          id="senha"
          placeholder="senha"
        />
        <button id="btnImagem" class="btn btn-primary btn-block m-2">
          Selecionar Imagem
        </button>

        <button id="btnGravar" class="btn btn-primary btn-block m-2">
          Gravar
        </button>

        <input type="file" />
      </div>
    </div>
  </body>
</html>

<script>
  document.querySelector('#btnImagem').addEventListener('click', () => {
    document.querySelector('input[type=file]').click();
  });

  document.querySelector('input[type=file]').addEventListener('change', (e) => {
    console.log(e.target.files[0]);
    const uploadTask = storageRef
      .child('imagens/' + e.target.files[0].name)
      .put(e.target.files[0]);
    uploadTask.on(
      'state_changed',
      (snapshot) => {
        const progress =
        
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100;

        console.log('Upload is ' + progress + '% done');

      },
      (erro) => {},
      () => {
        uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
          console.log('File available at', downloadURL);
        });
      }
    );
  });

  document.querySelector('#btnGravar').addEventListener('click', () => {
    const email = document.querySelector('input[type=email]').value;
    const senha = document.querySelector('input[type=password]').value;
    const nome = document.querySelector('input[type=text]').value;

    if (auth.currentUser) {
      const credenciais = obterCredenciais(email, senha);
      linkarUsuario(credenciais);
    } else {
      auth.createUserWithEmailAndPassword(email, senha).then((credentials) => {
        console.log(credentials.user.uid);
        gravarUsuarioNaBase(credentials.user.uid, nome, email);
      });
    }
  });

  function obterCredenciais(email, senha) {
    return firebase.auth.EmailAuthProvider.credential(email, senha);
  }

  function linkarUsuario(credenciais) {
    auth.currentUser
      .linkWithCredential(credenciais)
      .then((cred) => {
        const user = cred.user;
        gravarUsuarioNaBase(user.uid, nome, email);
      })
      .catch((error) => {
        console.log(error);
      });
  }

  function gravarUsuarioNaBase(uid, nome, email) {
    db.ref('usuarios').child(uid).set({ uid, nome, email });
  }
</script>

1

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *