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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51789871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:53:48  来源:igfitidea点击:

Download file from http post request - Angular 6

javascriptnode.jsangulartypescriptmean-stack

提问by PierBJX

UPDATED with res.send(data) instead of res.json(data)

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

Using Angular 6 and NodeJS I am doing a web application. I am trying to download a file from a http post request.

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

I send a request to the server like this. From my component I call a function in a service. In the component, I susbscribe to have the answer of the server and when I have it I create a new Blob with the response and I Use FileSaver to download the pdf.

我像这样向服务器发送请求。从我的组件中,我调用了服务中的一个函数。在组件中,我订阅服务器的答案,当我得到它时,我用响应创建一个新的 Blob,然后使用 FileSaver 下载 pdf。

Now, when I received the answer from the server, the client sees it like an error whereas the status is 200. The error message is: "Http failure during parsing for http://localhost:3000/api/experiment/regression"See the screenshot below.

现在,当我从服务器收到答案时,客户端将其视为错误,而状态为 200。错误消息是: “解析http://localhost:3000/api/experiment/regression 时出现Http failure ”请参见下面的截图。

Component.ts

组件.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);
    }
  );

API.Service.ts

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));
  }

Then from the server, it executes some code with the data sent and generates a PDF file. Then, I would like to send the pdf as a response to the client. I tried like this:

然后从服务器,它使用发送的数据执行一些代码并生成一个 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);
});

In the client, I have the answer. The console log is: console log

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

回答by PierBJX

Finally, I found a video tutorial and it was very basic.

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

Node.js Server:

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);
};

Angular Component:

角度组件:

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);
    }
  );
}

Angular Service:

角度服务:

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")
  });
}