【问题标题】:Displaying text from a text-file on Firebase storage在 Firebase 存储上显示文本文件中的文本
【发布时间】:2019-03-07 03:51:45
【问题描述】:

我完全是 Firebase 的业余爱好者。我的短期目标是从我上传到 Firebase 的文本文件中读取数据。这是代码(从文档复制粘贴):

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

我从这里开始不和。如何阅读此文件并将文本复制到我的页面中?到目前为止我的代码是否正确?

谢谢。

【问题讨论】:

  • 您找到解决问题的方法了吗?我想做类似的事情。
  • @Spurious 我还没有找到解决方案。

标签: firebase firebase-storage


【解决方案1】:

我花了几天时间想办法解决这个问题,但后来我意识到,我们得到了 url,所以我们可以在 url 上创建一个获取请求并以文本形式获取响应。我实际上是用 angular 来做的,但你可以用 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));
      }
    );
  };

使用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);
    });
  });
});

一个JSfiddle 来帮助你。将小提琴的fetch 中的链接替换为您从firebase 获得的downloadUrl

更新: 如果遇到CORS 错误,请务必先按照these 步骤操作。

【讨论】:

  • 谢谢,冠军!我为此苦苦挣扎,async 管道没有显示 CORS 错误。我也没有考虑检查我的网络选项卡。我认为在我最初获取下载网址的调用中路径错误。
【解决方案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");
         });

【讨论】:

    猜你喜欢
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2018-08-11
    • 2018-01-19
    • 2021-11-14
    • 2019-08-29
    相关资源
    最近更新 更多