我正在使用expressjs开发我的应用程序。我已经编写了一个使用res.download(filepath, filename)
在客户端下载文件的服务。以下是我的服务。
router.route('/downloadFile').get(function(req,res){
var filter = url.parse(req.url, true).query.filter;
Model.find({label:filter}).exec()
.catch(function(err){
console.error(err);
})
.then(function(data){
var fileTobeDownloadedPath = foo(); //returns a zip file path which belongs to a location in my temp folder in project
res.download(fileTobeDownloadedPath, path.parse(fileTobeDownloadedPath).base);
});
});
这是我的前端javascript代码
$(document).on('click','#btnDownload', function(event) {
// I am populating the values of the array using some javascript query
window.open('/downloadFile?filter=' + angular.element('[ng-controller=mainCtrl]').scope().mainCtrlObj.modalContent.label +
'&tags=' + angular.element('[ng-controller=mainCtrl]').scope().mainCtrlObj.modalContent.tags.toString() +
'&sizes=' + sizes.toString() + '&formats=' + formats.toString());
});
根据用户在前端选中的复选框,服务将调用res.download,并将zip文件路径作为参数或单个文件路径。但当我选择多个选项并单击下载时,我应该下载一个zip文件。
文件当前正在下载,但zip文件大小为0字节,并且zip文件中没有文件。
请告诉我出了什么问题。提前感谢。
可能太晚了,但这不会起作用,因为函数没有定义为async,使其成为async。基本上,您已经开始将文件转换为zip,甚至在完成zip文件之前就发送响应。
所以,
router.route('/downloadFile').get(function(req,res){
var filter = await url.parse(req.url, true).query.filter;
Model.find({label:filter}).exec()
.catch(function(err){
console.error(err);
})
.then(async function(data){
var fileTobeDownloadedPath = await foo(); //returns a zip file path
which belongs to a location in my temp folder in project
res.download(fileTobeDownloadedPath,
path.parse(fileTobeDownloadedPath).base);
});
});
这应该有效,如果不起作用,你必须尝试其他方法使其同步。