Paul Kruger
Paul Kruger

Reputation: 2314

Angular and Nodejs basic file download

Could someone show me an example of a user basic file download using Node and Angular please. I understand it like this, but this is not working:

Nodejs:

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

Angular 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(...) ?`
});

Here are possible answers, but they are so complex, could someone just give me a super basic example (basically what I have here, but a working version). The easiest solution please.

How do I download a file with Angular2

Angular download node.js response.sendFile

Upvotes: 0

Views: 434

Answers (1)

Kashkashio
Kashkashio

Reputation: 514

There you go..

Node.js Server:

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

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

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

Component Angular:

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

Service Angular:

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

Upvotes: 2

Related Questions