Angular2 到 export/download json 文件

Angular2 to export/download json file

我正在使用 angular 2。我想提供下载 JSON 文件的功能。

就像我对 res = {bar : foo} 的响应,然后我想创建 json 文件,其中将包含此响应,可以在 button/anchor 单击时下载。

任何帮助将不胜感激。

比想象中简单。

constructor(private sanitizer: DomSanitizer){}

    generateDownloadJsonUri() {
        var theJSON = JSON.stringify(this.resJsonResponse);
        var uri = this.sanitizer.bypassSecurityTrustUrl("data:text/json;charset=UTF-8," + encodeURIComponent(theJSON));
        this.downloadJsonHref = uri;
    }

在模板中包含

<a class="btn btn-clear" title="Download JSON" [href]="downloadJsonHref" download="download.json"></a>

您可以使用 DomSanitizer: https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

需要导入语句:

import {enter code here DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';
constructor(private sanitizer: DomSanitizer){}

generateDownloadJsonUri() {
    var theJSON = JSON.stringify(this.resJsonResponse);
    var uri = this.sanitizer.bypassSecurityTrustUrl("data:text/json;charset=UTF-8," + encodeURIComponent(theJSON));
    this.downloadJsonHref = uri;
}

当我的 json 太大时我遇到了一些问题,我在 Ankur Akvaliya 答案中添加了一个 Blob 对象并且它有效!!

generateDownloadJsonUri() {
    let theJSON = JSON.stringify(this.resJsonResponse);
    let blob = new Blob([theJSON], { type: 'text/json' });
    let url= window.URL.createObjectURL(blob);
    let uri:SafeUrl = this.sanitizer.bypassSecurityTrustUrl(url);
    this.downloadJsonHref = uri;
}

纯 JavaScript 就可以了。

downloadJson(myJson){
    var sJson = JSON.stringify(myJson);
    var element = document.createElement('a');
    element.setAttribute('href', "data:text/json;charset=UTF-8," + encodeURIComponent(sJson));
    element.setAttribute('download', "primer-server-task.json");
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click(); // simulate click
    document.body.removeChild(element);
}

您可以使用 DomSanitizer 中的 bypassSecurityTrustUrl() 方法执行此操作。

app.component.ts

export class AppComponent {
  downloadUrl;
  filename = "";
  constructor(private sanitizer: DomSanitizer) {
    this.generateUrl();
  }

  generateUrl() {
    var res = { appname: "ABCD", appid: 1234 };
    this.filename = res.appname + res.appid;
    var data = JSON.stringify(res);
    var url = this.sanitizer.bypassSecurityTrustUrl(
      "data:text/json;charset=UTF-8," + encodeURIComponent(data)
    );
    this.downloadUrl = url;
  }
}

app.component.html

<a [href]="downloadUrl" download="{{filename}}.json">Download</a>

请注意,只有 Json 创建文件和 link 下载 link 所需的代码片段。

另外,文件名可以随心所欲。目前,文件名是使用 json 数据创建的。

如果您有兴趣查看现场演示,那么您可以使用以下 link。

https://codesandbox.io/s/download-json-angular-k9fvz?file=/src/app/app.component.ts