【问题标题】:Sending get request to download file generated on the server side发送获取请求以下载服务器端生成的文件
【发布时间】:2021-04-21 11:51:24
【问题描述】:

我正在学习平均堆栈,并且我在应用程序的服务器端生成了一个文件,我打算在单击按钮时从我的角度前端下载该文件。 但是当我单击按钮时没有任何反应,我检查我的后端文件是否成功生成并且一切正常。 当我从浏览器访问“localhost:port/generate-file”时,文件会成功生成并下载,所以我想我在角度部分有一些问题。

这是我使用的代码:

ts

  downloadFile(): any {
    return this.http
      .get('http://localhost:4000/generated-file', { responseType: 'blob' })
      .subscribe();
  }

标记

  <button class="button" (click)="downloadFile()">

提前谢谢你。

【问题讨论】:

  • 首先检查您是否通过console.log在角端获得响应,如果是,则正确订阅您的响应。 .subscribe() 之后我什么也没看到。阅读 abt 如何订阅响应。
  • 嘿@VinaySomawat 谢谢你的回复,我在控制台登录了console.log( this.http.get('http://localhost:4000/generated-file', { responseType: 'blob', }),我得到了一个可观察的对象
  • 你做错了!阅读如何订阅响应。 stackoverflow.com/questions/51230312/angular-subscribe-response

标签: javascript node.js angular express mean-stack


【解决方案1】:

如果您的 API 工作正常(如果它以 blob 形式返回文件),您可以使用 file-saver.js 下载它。

this.http.get('http://localhost:4000/generated-file', {
    responseType: 'blob'
}).subscribe(
    response => {
        saveAs(response, 'filename')
    }
);

查看link 的简单示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 2016-02-10
    • 2020-04-08
    • 1970-01-01
    • 2023-03-30
    • 2019-07-08
    • 2016-10-23
    相关资源
    最近更新 更多