node.js - 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(...) ?`
});
这是可能的答案,但它们太复杂了,有人可以给我一个超级基本的例子(基本上我在这里有什么,但是一个工作版本)。请提供最简单的解决方案。
解决方案
给你。。
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")
});
}
推荐阅读
- php - 是什么导致 object(mysqli_result)#3 (5) 在屏幕上显示?
- azure - Azure ServiceBusEnvironment.SystemConnectivity.Mode 指南
- arcgis - CityEngine2014.0 中的属性连接失败
- excel - 在 excel VBA 2016 中找不到方法或数据成员错误
- python - 仅删除组内的重复项
- java - 以编程方式获取增量布局 ID
- linux - Perl - 计算文件的字数
- c# - 如何检查文件中是否已存在用户名
- algorithm - 对于 MST,以下哪些选项是正确的?
- javascript - 当我向 /api/users/login 发送 POST 请求时未定义用户