发送get请求下载服务器端生成的文件

Sending get request to download file generated on the server side

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

这是我使用的代码:

ts

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

标记

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

提前致谢。

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

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

请参阅此 link 以获取简单示例。