首页 > 解决方案 > Angular 和 Nodejs 基本文件下载

问题描述

有人可以给我看一个使用 Node 和 Angular 下载用户基本文件的例子吗?我是这样理解的,但这不起作用:

节点:

// Does it matter that it is a post and not a get?
app.post('/some-api', someData, (request, response) => {
    response.download('file/path/mytext.txt');
});

角度 2+:

this.httpclient.post<any>('.../some-api', {...data...}).subscribe(response => {
  console.log(response);
  // This throws an error, but even if it doesn't,
  // how do I download the Nodejs `response.download(...) ?`
});

这是可能的答案,但它们太复杂了,有人可以给我一个超级基本的例子(基本上我在这里有什么,但是一个工作版本)。请提供最简单的解决方案。

如何使用 Angular2 下载文件

Angular 下载 node.js response.sendFile

标签: node.jsangular

解决方案


给你。。

Node.js 服务器:

const express = require("express");
const router = express.Router();

router.post("/experiment/resultML/downloadReport",downloadReport);

const downloadReport = function(req, res) {
  res.sendFile(req.body.filename);
};

组件角度:

  import { saveAs } from "file-saver"
  download() {
    let filename = "/Path/to/your/report.pdf";
    this.api.downloadReport(filename).subscribe(
      data => {
        saveAs(data, filename);
      },
      err => {
        alert("Problem while downloading the file.");
        console.error(err);
      }
    );
  }

服务角度:

  public downloadReport(file): Observable<any> {
    // Create url
    let url = `${baseUrl}${"/experiment/resultML/downloadReport"}`;
    var body = { filename: file };

    return this.http.post(url, body, {
      responseType: "blob",
      headers: new HttpHeaders().append("Content-Type", "application/json")
    });
  }

推荐阅读