首页 > 解决方案 > 在 Firebase 存储上显示文本文件中的文本

问题描述

我完全是 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();
});

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

谢谢。

标签: firebasefirebase-storage

解决方案


我花了几天时间研究如何解决这个问题,但后来我意识到,我们得到了 url支持,所以我们可以创建一个 get 请求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来帮助你。将小提琴中的链接替换为fetchdownloadUrl从 firebase 获得的链接。

更新:如果您遇到错误, 请务必先执行这些步骤。CORS


推荐阅读