Angular 下载 node.js response.sendFile

Angular download node.js response.sendFile

目前我的 nodejs 服务正在这样做:

...
fs.writeFileSync('filelocation/data.xlsx', theData, 'binary');
reponse.sendFile('filelocation/data.xlsx');
reponse.download('filelocation/data.xlsx'); // I tried this one also
...

但是现在如何使用 HttpClient 从 Angular 前端下载它?这不起作用:

this.httpclient.get(url).subscribe(response => {
  console.log(response); // Or whatever I need to do to download the file
});

我想要调出文件资源管理器的调用,以便我可以保存文件。我如何让这个工作?如果您需要我提供更多信息,请告诉我。

创建一个 component.ts 并将文件名传递给 fileService。 在 fileService 内部创建下载功能并使用该功能将文件名传递给后端服务器。可以使用 'saveAs' 下载文件。安装 filesaver (npm install file-saver --save) 并在前端组件中导入 'saveAs'。

Download(filename){
    console.log(filename);
    this.fileService.download(filename).subscribe((data)=>{
        console.log(data);
        saveAs(data, filename);
    });
}

Component.ts

download(filename){
    const fileObj = {
        filename : filename
    };
    console.log(fileObj);
    return this.http.post(`http:localhost:3000/download`, fileObj, {
        responseType : 'blob',
    });
} 

fileService.ts

app.post('/download', (req, res, next) => {
    console.log('here');
    filepath = path.join(__dirname,'../uploadedFiles') + '/' + req.body.filename;
    console.log(filepath);
    res.sendFile(filepath);
});

Server.js