JavaScript将图像上传到Firebase数据库

时间:2017-11-29 21:41:09

标签: javascript firebase firebase-storage

我想知道是否有代码可以让我使用网页将图片上传到Firebase数据库。我已经看了很多,但我无法让它发挥作用。也许我需要jQuery。

我试过这个,但它没有用。这是代码开始的地方。 我想知道什么是缺失的,以及它的错误。



<html>

<head>
  <script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
  <title>ZeroToApp</title>
  <style>
    #messages {
      width: 40em;
      border: 1px solid grey;
      min-height: 20em;
    }
    
    #messages img {
      max-width: 240px;
      max-height: 160px;
      display: block;
    }
    
    #header {
      position: fixed;
      top: 0;
      background-color: white;
    }
    
    .push {
      margin-bottom: 2em;
    }
    
    @keyframes yellow-fade {
      0% {
        background: #f2f2b8;
      }
      100% {
        background: none;
      }
    }
    
    .highlight {
      -webkit-animation: yellow-fade 2s ease-in 1;
      animation: yellow-fade 2s ease-in 1;
    }
  </style>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Step 0: HTML defined, variables for elements
      var messagesList = document.getElementById('messages'),
        textInput = document.getElementById('text'),
        sendButton = document.getElementById('send'),


        usernameElm = document.getElementById('username'),
        password = document.getElementById('password'),
        username = "Web";
      var config = {
        apiKey: "AIzaSyCvAEr1Enh_lwXzkxSe1EBmE8JYLpD2UrI",
        authDomain: "fir-web-learn-35260.firebaseapp.com",
        databaseURL: "https://fir-web-learn-35260.firebaseio.com",
        projectId: "fir-web-learn-35260",
        storageBucket: "fir-web-learn-35260.appspot.com",
        messagingSenderId: "685977302529"
      };
      // Get the Firebase app and all primitives we'll use
      var app = firebase.initializeApp(config),
        database = app.database(),
        auth = app.auth(),
        storage = app.storage();

      var databaseRef = database.ref().child('chat');
      sendButton.addEventListener('click', function(evt) {
        var chat = {
          name: username,
          message: textInput.value
        };
        databaseRef.push().set(chat);
        textInput.value = '';
      });
      // Listen for when child nodes get added to the collection
      databaseRef.on('child_added', function(snapshot) {
        // Get the chat message from the snapshot and add it to the UI
        var chat = snapshot.val();
        addMessage(chat);
      });

      // Show a popup when the user asks to sign in with Google

      // Allow the user to sign out

      // When the user signs in or out, update the username we keep for them
      auth.onAuthStateChanged(function(user) {
        if (user) {
          setUsername(user.displayName);
        } else {
          // User signed out, set a default username
          setUsername("Web");
        }
      });

      function handleFileSelect(e) {
        var file = e.target.files[0];
        // Get a reference to the location where we'll store our photos
        var storageRef = storage.ref().child('chat_photos');

        // Get a reference to store file at photos/<FILENAME>.jpg
        var photoRef = storageRef.child(file.name);
        // Upload file to Firebase Storage
        var uploadTask = photoRef.put(file);
        uploadTask.on('state_changed', null, null, function() {
          // When the image has successfully uploaded, we get its download URL
          var downloadUrl = uploadTask.snapshot.downloadURL;
          // Set the download URL to the message box, so that the user can send it to the database
          textInput.value = downloadUrl;
        });
      }
      file.addEventListener('change', handleFileSelect, false);

      function setUsername(newUsername) {
        if (newUsername == null) {
          newUsername = "Web";
        }
        console.log(newUsername);
        username = newUsername;
        var isLoggedIn = username != 'Web';
        usernameElm.innerText = newUsername;
      }

      function addMessage(chat) {
        var li = document.createElement('li');
        var nameElm = document.createElement('h4');
        nameElm.innerText = chat.name;
        li.appendChild(nameElm);
        li.className = 'highlight';
        if (chat.message.indexOf("https://firebasestorage.googleapis.com/") == 0 ||
          chat.message.indexOf("https://lh3.googleusercontent.com/") == 0 ||
          chat.message.indexOf("http://pbs.twimg.com/") == 0 ||
          chat.message.indexOf("data:image/") == 0) {
          var imgElm = document.createElement("img");
          imgElm.src = chat.message;
          li.appendChild(imgElm);
        } else {
          var messageElm = document.createElement("span");
          messageElm.innerText = chat.message;
          li.appendChild(messageElm);
        }
        messagesList.appendChild(li);
        li.scrollIntoView(false);
        sendButton.scrollIntoView(false);
      }
      //window.app = app; // NOTE: just for debugging
      //for (var i=0; i < 10; i++) addMessage({ name: "Web", message: ''+i });
      setUsername('Web');
    });
  </script>
</head>

<body>

  <div class="push"></div>
  <ul id='messages'></ul>
  <div id='footer'>
    <input type="file" id="file" name="file" />
    <input id='text'>
    <button id='send'>Send</button>
  </div>
</body>

</html>
&#13;
&#13;
&#13;

提前致谢。

0 个答案:

没有答案