【问题标题】:Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app在 Angular 应用程序中将 json 文件(从 json-server)下载为 txt 或 json 或 csv 文件
【发布时间】:2021-12-01 16:53:39
【问题描述】:

我在我的 Angular 应用程序中安装了json-server,它使我能够通过假 json API 将表单(由用户填写)保存到 json 文件中:

{
  "extracts": [
    {
      "contentName": "xxx",
      "contentType": "xxx",
      "contentToStore": "xxx",
      "id": 1
    }
  ]
}

我也可以在我的http://localhost:3000/extracts看到结果

在我的html 模板中,我的表单已提交:

<form #postForm="ngForm" (ngSubmit)="onSubmitExtractions(postForm.value)">

在对应的组件中,我写了这段代码:

onSubmitExtractions(postData: Post) {
    
    this
      .dbService
      .submitExtractions(postData)
      .subscribe(
        postData => {
          this.jsonPosts.push(postData);
        }
    );
    
    this
      .dbService
      .downloadExtractions(postData);
}

第一个 sn -p 写入 json 文件,在服务脚本中有这段代码:

submitExtractions(post: Post): Observable<Post> {
    return this.httpClient.post<Post>(this.apiUrl, post, httpOptions);
}

这工作正常,我在一个 json 文件(假 json 服务器数据库)中得到结果,第二个 sn-p 应该下载这个文件,它在服务脚本中的代码是这样的:

downloadExtractions(post: Post) {

    const blob = new Blob([JSON.stringify(post, null, 2)], { type: 'application/json' });

    if (blob) {
      this.downloaded = 'The blob contains ' + blob.size + ' byte!';
    } else {
      this.downloaded = 'The download failed!';
    }
}

为了实际下载 json 内容,我在代码中遗漏了什么?如何将此内容下载为 csvjson 甚至 text 文件?

【问题讨论】:

    标签: html json angular typescript json-server


    【解决方案1】:

    请尝试此解决方案。它使用相同的 blob 只是一些常量数据。

    在html中

    <a [href]="fileUrl" download="file.txt">DownloadFile</a>
    

    在component.ts中

    export class AppComponent implements OnInit {
      name = 'Angular 5';
      fileUrl;
      constructor(private sanitizer: DomSanitizer) {  }
      ngOnInit() {
        const data = 'some text';
        const blob = new Blob([data], { type: 'application/octet-stream' });
    
        this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
      }
    
    }
    

    如需参考,请访问:

    https://stackblitz.com/edit/angular-blob-file-download-text-file?file=app%2Fapp.component.ts

    【讨论】:

    • @Trouble 谢谢。这很有帮助。我不明白的是fileUrl。这究竟是什么网址?当我在我的方法中尝试您的代码时,下载的文件包含我的index.html 的内容。 fileUrl 应该是我的apiUrl,这是json-server 在我的应用程序中创建的 json 文件的 url?
    • 好的,fileUrl 只是在这里调用 DOMSanitizer 的处理程序。 window.URL.createObjectURL(blob) 正在参考您的应用程序所在的当前 url 创建一个新 url,并将对象(此处为 blob)添加到该 url。最后,fileUrl 会绕过您当前的安全性并将此 url 传递给 DOM,然后由 DOM 为您下载文件。希望它有意义,您可以使用 console.log() 检查变化。如果你想从 api 获取数据,你可以得到它来创建 blob,然后将 blob 传递到这里下载。
    猜你喜欢
    • 2015-06-27
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    相关资源
    最近更新 更多