Google Cloud Storage - How to Upload content directly from browser (JavaScript)

Viewed 537

How to upload content directly from browser (JavaScript) to GC Storage? Is there some simple way to do it with token (in URL/cookies) or alike?

Note: no intermediary systems (like URL signers) are considered. I am looking for a way to send request from JS and and process it at GC Storage.

If no, what is the simplest solution do you know about to not introduce too many dependencies and complexity?

1 Answers

It's very easy. You can do it from the web with the Firebase JavaScript SDK.

https://firebase.google.com/docs/storage/web/upload-files

Code from the docs

var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);
  });
});
Related