如何解决从AngularJS中的Node.js接收文本流
我有一个使用MongoDB作为数据库,后端使用Node.js,前端使用AngularJS构建的应用程序。 我需要从MongoDB中将大量数据导出到cvs格式文件,并使用户可以下载它。我的第一个实现使用流(Mongoose)从MongoDB中检索数据,使用可写流保存文件,然后将路径返回到AngularJS下载。
此方法无法处理较大的文件,因为写入时间更长,并且AngularJS中的原始请求超时。我将后端更改为,而不是将文件写入磁盘,而是将数据流式传输到响应,以便AngularJS可以按块接收它们并下载文件。
Node.js
router.get('/log/export',async(req: bloo.BlooRequest,res: Response) => {
res.setHeader('Content-Type','text/csv');
res.setHeader('Content-Disposition','attachment; filename=\"' + 'download-' + Date.now() + '.csv\"');
res.setHeader('Cache-Control','no-cache');
res.setHeader('Pragma','no-cache');
const query = req.query;
const service = new LogService();
service
.exportUsageLog(req.user,query)
.pipe(res);
});
public exportUsageLog(user: User,query: any) {
let criteria = this.buildQuery(query);
let stream = this.dao.getLogs(criteria);
return stream
.pipe(treeTransform)
.pipe(csvTransform);
}
public getLogs(criteria: any): mongoose.QueryStream {
return this.logs
.aggregate([
{
'$match': criteria
},{
'$lookup': {
'from': 'users','localField': 'username','foreignField': '_id','as': 'user'
}
}
])
.cursor({})
.exec()
.stream();
}
此Node.js实现正常工作,因为我可以使用Postman应用程序查看数据。
我的问题是如何在AngularJS中接收这些块,将它们写入文件,并在更改后端以流式传输数据而不是仅返回文件路径之后,在客户端开始下载。
我当前的AngularJS代码:
cntrl.export = () => {
LogService
.exportLog(cntrl.query)
.then((res: any) => {
if (res.data) {
console.dir(res.data);
let file = res.data;
let host = location.protocol + "//" + window.location.host.replace("www.","");
let path = file.slice(7,32);
let fileName = file.slice(32);
let URI = host + "/"+ path + fileName;
let link = document.createElement("a");
link.href = URI;
link.click();
}
})
.catch((err: any) => console.error(err));
}
angular
.module('log',[])
.factory('LogService',LogService);
function LogService(constants,$resource,$http) {
const
ExportLog = $resource(constants.api + 'modules/log/export');
exportLog(query: any) {
return ExportLog.get(query,res => res).$promise;
},};
}
使用上面的代码,“ res”未定义。
我该如何实现?
谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。