node.js - Angular 下载 node.js response.sendFile

标签 node.js angular-httpclient

目前我的 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 内部创建下载功能并使用该功能将文件名传递给后端服务器。可以使用“另存为”下载文件。安装文件保护程序(npm install file-saver --save)并在前端组件中导入“saveAs”。

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

组件.ts

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

文件服务.ts

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

服务器.js

关于node.js - Angular 下载 node.js response.sendFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56231765/

相关文章:

node.js - 非阻塞 MongoDB + NodeJS

ios - 如何使用 node.js 和 socket.io 将文件从 iPhone 发送到另一部 iPhone?

angular - HttpRequest 和 reportProgress 不起作用或弄乱了我的请求

angular - http.get() 不返回可观察值

javascript - 使用 HttpClient 的模块是否应该在导入中声明 HttpClientModule?

javascript - 使用 Angular HttpClient 在 DELETE 请求完成后执行某些操作

angular - 带有 HttpParams 的 HttpClient POST

javascript - Express + Mongoose Rest 可扩展项目

javascript - 无法从js对象中删除键值对

node.js - 有没有办法从 node.js 同步调用 AWS Lambda?