将 JSON 数组下载到文件

Download JSON array to file

以下的推荐方式是什么:

应通过按钮下载一组实体。该按钮称为 Download transactions 并且应该在不强迫用户 "right click and 'save site as...'".

的情况下执行此操作

我有一个实体 Transaction 和一个包含它的数组。

实体:

export class Transaction {
  title: string;
  category: string;
  period: string;
  value: string;
}

这是我最后一次尝试将此数组下载为文件:

  exportJson(): void {
    console.log(this.transactions)
    const c = JSON.stringify(this.transactions);
    const file = new Blob([c], {type: 'text/json'});
    const fileURL = URL.createObjectURL(file);
    location.href = fileURL;
  }

这会在当前 window 中加载包含结果的选项卡,但会以纯文本而不是可下载文件的形式加载。

我知道有很多关于这个主题的问题,none 我发现对我有用。任何帮助表示赞赏! :)

以下函数可能是您要找的:

function download(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(blob, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(blob);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

然后

exportJson(): void {
    console.log(this.transactions)
    const c = JSON.stringify(this.transactions);
    const file = new Blob([c], {type: 'text/json'});
    download(file,"fileName.json");
  }