从http post请求下载文件 - Angular 6

Pie*_*BJX 3 javascript node.js typescript mean-stack angular

使用res.send(数据)而不是res.json(数据)更新

使用Angular 6和NodeJS我正在做一个Web应用程序.我正在尝试从http发布请求下载文件.

我像这样向服务器发送请求.从我的组件我调用服务中的函数.在组件中,我怀疑有服务器的答案,当我有它时,我创建一个新的Blob与响应和我使用FileSaver下载PDF.

现在,当我从服务器收到答案时,客户端将其视为错误,而状态为200.错误消息为: "解析http:// localhost:3000/api/experiment/regression期间的Http失败" 请参阅下面的截图.

Component.ts

this.api.postML(this.regression).subscribe(
    res => {
      console.log(res);
      let pdf = new Blob(res.data, { type: "application/pdf" });
      let filename = "test.pdf";
      FileSaver.saveAs(pdf, filename);
    },
    err => {
      alert("Error to perform the regression");
      console.log(err);
    }
  );
Run Code Online (Sandbox Code Playgroud)

API.Service.ts

  public postML(data): Observable<any> {
    // Create url
    let url = `${baseUrl}${"experiment/regression"}`;

    let options = {
      headers: { "Content-Type": "application/json", Accept: "application/pdf" }
    };
    // Call the http POST
    return this.http
      .post(url, data, options)
      .pipe(catchError(this.handleError));
  }
Run Code Online (Sandbox Code Playgroud)

然后从服务器,它执行一些代码与发送的数据,并生成PDF文件.然后,我想将pdf作为对客户的回复发送.我试过这样的:

fs.readFile("/home/user/test.pdf", function(err, data) {
  let pdfName = "Report.pdf";
  res.contentType("application/pdf");
  res.set("Content-Disposition", pdfName);
  res.set("Content-Transfer-Encoding", "binary");
  console.log(data);
  console.log("Send data");
  res.status(200);
  res.send(data);
});
Run Code Online (Sandbox Code Playgroud)

在客户端,我有答案.控制台日志是: 控制台日志

Pie*_*BJX 16

最后,我找到了一个视频教程,它非常基础.

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);
};
Run Code Online (Sandbox Code Playgroud)

组件角度:

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);
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

服务角度:

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")
  });
}
Run Code Online (Sandbox Code Playgroud)

  • “ saveAs”函数从何而来? (3认同)