Displaying text from a text-file on Firebase storage

*爱你&永不变心* 提交于 2021-02-08 10:29:45

问题


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.


回答1:


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.




回答2:


<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");
         });


来源:https://stackoverflow.com/questions/51117119/displaying-text-from-a-text-file-on-firebase-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!