【问题标题】:How to upload json file to Firebase Realtime database angular 8如何将 json 文件上传到 Firebase Realtime 数据库 Angular 8
【发布时间】:2021-11-12 07:08:53
【问题描述】:

我正在使用以下两个函数将 excel 表转换为 json,问题我如何才能将这个 json 文件直接从我的应用程序上传到 Firebase Realtime 数据库?

我想从我的应用程序中添加此功能

onFileChange(ev) {
  let workBook = null;
  let jsonData = null;
  const reader = new FileReader();
  const file = ev.target.files[0];
  reader.onload = (event) => {
    const data = reader.result;
    workBook = XLSX.read(data, { type: 'binary' });

    jsonData = workBook.SheetNames.reduce((initial, name) => {
      const sheet = workBook.Sheets[name];
      initial[name] = XLSX.utils.sheet_to_json(sheet);
      return initial;
    }, {});
    const dataString = JSON.stringify(jsonData);
    document.getElementById('output').innerHTML = dataString.slice(0, 300).concat('...');
    this.setDownload(dataString);
  };
  reader.readAsBinaryString(file);
}


setDownload(data) {
  this.willDownload = true;
  setTimeout(() => {
    const el = document.querySelector('#download');
    el.setAttribute('href', `data:text/json;charset=utf-8,${encodeURIComponent(data)}`);
    el.setAttribute('download', 'xlsxtojson.json');
  }, 1000);
}

【问题讨论】:

标签: angular typescript firebase-realtime-database


【解决方案1】:

正如 Frank 所说,Angular 没有什么特别之处,因为您可以按照文档将 JSON 上传到 RTDB。

但是,在使用 Angular 时,您需要使用 angular/fire 包,它是用于 Angular 和 Firebase 开发的官方库。

在您的构造函数中,您将导入 AngularFireDatabase 类

constructor(private db: AngularFireDatabase) {}

然后这是上传数据的函数:

  async uploadJSONToRTDB(yourDataHere: any): Promise<void> {
    // reference the node
    const ref = this.db.database.ref('ref/to/your/node');
    await ref.set(yourDataHere);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多