0

I am a total amateur to Firebase. My short-term objective here is to read data from a text file that I uploaded onto Firebase. This is the code (copy-pasted from the docs):

storageRef.child('images/stars.jpg').getDownloadURL().then(function (url) {
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function(event) {
    var blob = xhr.response;
  };
  xhr.open('GET', (/*here I put the url of the file*/));
  xhr.send();
});

I am at odds from here. How do I read this file and copy the text into my page? Is my code correct so far?

Thanks.

Aravind Suresh
  • 1,153
  • 1
  • 19
  • 30

2 Answers2

3

I spend days figuring out how to solve this problem, but then I realized, we are getting the url back, so we can just create a get request on that url and get the response as text. I actually did this using angular, but you can do the same with fetch

ngOnInit() {
    const ref = this.storage.ref('array.txt');
    ref.getDownloadURL().subscribe(data => {
        this.http.get(data, { responseType: 'text' as 'json' }).subscribe(text => console.log(text));
      }
    );
  };

Using fetch

const ref = this.storage.ref('array.txt');
ref.getDownloadURL().subscribe(data => {
  fetch(data)
  .then(function(response) {
    response.text().then(function(text) {
      console.log(text);
    });
  });
});

A JSfiddle to help you out. Replace the link in the fiddle's fetch with the downloadUrl you're getting from firebase.

UPDATE: Make sure follow these steps first, if you're getting CORS error.

kinny94
  • 366
  • 6
  • 22
  • 1
    Thanks, champ! I was struggling a lot with this and the `async` pipe doesn't display the CORS errors. I didn't think about checking my Network tab either. I thought the path was wrong in my original call for getting the download url. – Ruben Szekér Apr 25 '21 at 15:13
0
<object id="linkbox"width="100%" height="100%" style="border: 2px solid red;"> </object>


     storageRef.child('documents/'+fileName+".txt").getDownloadURL().then(function(url) {

          console.log('File available at', url);

          var db= document.getElementById('linkbox');
          db.data=url;

        }).catch(function(error) {
           // Handle any errors
           console.log("Not found");
         });