Firebase Storage with Web Component

MIT provide a firebase component for managing key:value pairs but do not provide a component for accessing firebase storage. There is an extension available for firebase storage. I have worked up a solution that just works with the web component and an html file (needed for firebase configuration) and use Juan's base64 extension to encode the file to be stored, and the webviewstring to send data to the html file, and send back the download url for the uploaded file.

HTML

<!DOCTYPE html>
<html>
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<meta charset="utf-8">

<head>
  <title>FB-STORAGE-AI2</title>
  
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-storage.js"></script>
 
</head>

<body>

<script>

//get webviewstring list from app
var wvstr = window.AppInventor.getWebViewString();

//set the firebase configuration from webviewstring
var firebaseConfig = {
  apiKey: wvstr.split(",")[0],
  authDomain: wvstr.split(",")[1],
  databaseURL: wvstr.split(",")[2],
  projectId: wvstr.split(",")[3],
  storageBucket: wvstr.split(",")[4],
};

var method = wvstr.split(",")[5];

//file data, base64 string - fileUrl for download
var filebase64 = wvstr.split(",")[6];
var filename = wvstr.split(",")[7];
var mimetype = wvstr.split(",")[8];
var dir = wvstr.split(",")[9];

//initialise firebase and storage reference
firebase.initializeApp(firebaseConfig);
var stor = firebase.storage();

//upload file and return url to webviewstring
if ( method  == "UPLOAD" ) {
  var storageRef = stor.ref();
 var metadata = { contentType: mimetype,};

 var uploadTask = storageRef.child(dir + '/' + filename).putString(filebase64, 'base64', metadata).then(function() {
   storageRef.child(dir + '/' + filename).getDownloadURL().then(function(downloadURL) {
   window.AppInventor.setWebViewString(downloadURL);
  });
 });
};

</script>
</body>

</html>


BLOCKS

This example runs with the rules for firebase storage set as "allow read, write: if true;"

It is possible to do the same thing with authenticated users, there is another post that shows how to authenticate a user, using just the web component and html. These can be combined....

Firebase Sign Up, In and Out with Web component and HTML

Also see: