Search code examples
javascriptfirebasegoogle-cloud-platformgoogle-cloud-storagefirebase-storage

Function when file upload is complete


I'm using JavaScript to upload a file to Firebase Storage. I don't know how to do a function when the file upload is complete. I tried to use .then but that didn't work.

So until I have another method, I keep checking every 10ms with a window.setInterval() if the value of the uploader is 100%

I'm using this script to check until it's done uploading:

task.on("state_changed",
  function progress(snapshot) {
    let percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    uploader.value = percentage;
    window.setInterval(function () {
      if (uploader.value === 100) {
        // The upload is complete!
        window.alert("Upload complete");
      };
    },10)
  }
);

But because I am doing it to fast, I'm getting this error in the Chrome console 276 times:

Unchecked runtime.lastError: This request exceeds the MAX_WRITE_OPERATIONS_PER_MINUTE quota.

Is there another way to check when my upload is completed?

(I am using Firebase Storage for my file hosting).

Thanks in advance!


Solution

  • Yikes, please don't use a setInterval like that. At best it wastes resources and make your laptop fan go all noisy on you, but more commonly it'll upset Chrome (as it does for you), or worse: your users.

    To detect when the upload is complete, you need to add additional callback methods to uploadTask.on('state_changed',:

    task.on("state_changed", function(snapshot) {
      let percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      uploader.value = percentage;
    }), function(error) {
      // Handle unsuccessful uploads
    }, function() {
      window.alert("Upload complete");
    });
    

    For more on see the Firebase documentation on uploading files, specifically the section on Monitoring upload progress. This page also includes a full example of uploading data and handling all possible outcomes.