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.

3 Answers3

4

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
  • 376
  • 1
  • 5
  • 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");
         });
0

It seems there's a slight confusion in your approach. The code you provided is meant for downloading and displaying an image (in this case, 'stars.jpg') from Firebase Storage, not for reading text data from a text file. To read text data from a file, you'll need to modify the code accordingly.

To read text data from a file in Firebase Storage, you can use the getDownloadURL() method to get the URL of the file, and then use that URL to fetch the contents of the file using an HTTP request. Here's how you can modify your code to achieve that:

// Replace 'your-file.txt' with the path to your text file in Firebase Storage
var fileRef = storageRef.child('your-file.txt');

fileRef.getDownloadURL().then(function (url) {
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'text'; // Set the response type to 'text' to get the file content as text
  xhr.onload = function(event) {
    var textContent = xhr.responseText; // This will contain the text data of the file
    // Do something with the text content, for example, display it on your page
    console.log(textContent); // You can see the text content in the browser console
  };
  xhr.open('GET', url); // Use the URL obtained from getDownloadURL() method
  xhr.send();
}).catch(function(error) {
  // Handle any errors that occur during the process
  console.error('Error fetching file:', error);
});

In this code, make sure to replace your-file.txt with the actual path to your text file in Firebase Storage. Once you run this code, the text content of the file will be fetched, and you can do further processing or display it on your page as needed.

Also, ensure that you have initialized storageRef correctly with the appropriate configuration for Firebase Storage before using it in this code. If you haven't done that already, refer to the Firebase documentation for setting up Firebase in your web application.

Rev9
  • 1
  • Welcome to Stack Overflow, Rev9. Your answer appears likely to have been written (entirely or partially) by AI (e.g., ChatGPT). A heads-up that [posting AI-generated content is not allowed here](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with any answer, I would encourage you to delete it. We do hope you'll be a part of our community and contribute with *your own*, quality posts in the future. Thanks! – NotTheDr01ds Jul 23 '23 at 15:25
  • **Readers should review this answer carefully and critically, as AI-generated information often contains fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly. – NotTheDr01ds Jul 23 '23 at 15:25