Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestorefirebase-storage

Firebase Storage uploading csv file


Ive created a WebApp via Firebase to Upload files to Cloud storage, however as i choose the file to upload, there is no action, the choose file action doesn't upload the file.

i've checked the following:

  • Storage rules: they are open
  • Browser settings: same issue across all browsers.

below is a my index.html file and hopefuly anyone can shed some slight on this strange issue?

<!doctype html>

<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Test Upload App</title>
  <style media="screen">
    body {
      display: flex;
      min-height: 100vh;
      width: 100%;
      padding: 0;
      margin: 0;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
    
    #uploader {
      -webkit-appearance: none;
      appearance: none;
      width: 50%;
      margin-bottom: 10px;
    }
  </style>
</head>

<body>

  <progress value="0" max="100" id="uploader">0%</progress>
  <input type="file" value="upload" id="fileButton" />

  <script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
  <script>
    // Initialize Firebase
    var config = {
      apiKey: "AIzaSyCA7XWfS7deQaYGgaUaTWK-xxxxxxxxxxxx",
      authDomain: "testapp.firebaseapp.com",
      databaseURL: "https://test-project.firebaseio.com",
      projectId: "testproject",
      storageBucket: "testbucket_inbound/mydata/",
    };
    firebase.initializeApp(config);

    //Get Elements
    var uploader = document.getElementById('uploader');
    var fileButton = document.getElementById('fileButton');

    //Listen for file selection
    fileButton.addEventListener('change', function(e) {
      // Get file
      var file = e.target.files[0];

      // Create storage ref
      var storageRef = firebase.storage().ref('mydata/' + file.name);

      // upload file
      var task = storageRef.put(file);

      // update progress bar
      task.on('state_changed',

        function progress(snapshot) {
          var percentage = (snapshot.bytesTransferred /
            snapshot.totalBytes) * 100;
          uploader.value = percentage;
        },

        function error(err) {

        },

        function complete() {

        }

      );
    });
  </script>
</body>

</html>


Solution

  • There is an error in the page you have deployed:

    you declare your button as follow in your HTML

    <input type="file" value="upload" id="filebutton" />
    

    but you set your EventListener on a button with an id with a uppercase B

    fileButton.addEventListener('change' , function(e) {
    

    Change to

    filebutton.addEventListener('change' , function(e) {
    

    and it should work.

    You can see the error from the browser Console: ReferenceError: fileButton is not defined

    Finally note that in the code of your question it is correct! You use fileButton at the two places.