我目前正在学习node.js,最近遇到一种情况,我想通过单击网页上的按钮来下载存储在服务器上的图像。我创建了一个端点, Controller 向该端点传递两个参数:
- 需要下载的图片名称(目录固定)
- 下载图像的名称
我已经尝试过 Download a file from NodeJS Server using Express 中给出的解决方案
我使用 Angular 来填充按钮并触发下载,如下所示:
<div class="btn-group" role="group" aria-label="Image tags">
<button ng-repeat="tag in imageTags" type="button" class="btn btn-outline-warning" ng-click="download(tag)">{{tag}}</button>
</div>
这是我的 Controller :
$scope.download = function(tagName) {
tagName = tagName.replace(/\W+/g, '-');
Clarifai.download(tagName, UploadSuccess.uploadedFile)
// UploadSuccess.uploadedFile contains the name of the file to be downloaded.
.success(function(data) {
//do something
});
}
它调用以下工厂方法:
download: function(tagName, imageName) {
return $http.get('/api/clarifai/tagDownload/' + tagName + "/" + imageName);
}
这是我的路线文件的相关部分:
app.get('/api/clarifai/tagDownload/:tagName/:imageName', function(req, res) {
// Ignore tagName for now.
console.log("Begin download");
var img = path.resolve('image_dump/OutputDump/' + req.params.imageName);
// Returns the expected path for the file
var filename = path.basename(img);
var mimetype = mime.lookup(img);
console.log(filename);
console.log(mimetype);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(img);
filestream.pipe(res);
res.on('finish', function(){
console.log("Download complete");
});
});
到目前为止,所有流程都有效,单击其中一个按钮后,我得到如下输出:
Begin download
Jon-1477683540996.jpg
image/jpeg
GET /api/clarifai/tagDownload/people/Jon-1477683540996.jpg 200 5.296 ms -
Download complete
但我在任何地方都看不到下载文件的迹象。任何浏览器上都没有对话框。到目前为止我读过的所有答案似乎都提到下载是由 pipe
调用处理的。但我没有成功。
我也尝试过res.download(img)
,但结果相同。
我的方法是使用 Controller 内的回调来处理这个问题。但我不知道该怎么做。我错过了什么/做错了什么?有人可以指出我正确的方向吗?
提前谢谢您。
最佳答案
为了完整起见,以下是我解决问题的方法:
在我的 Controller 中,而不是使用:
$http.get('/api/clarifai/tagDownload/' + tagName + "/" + imageName);
我必须这样做:
path = "/api/clarifai/tagDownload/" + tagName + "/" + imageName;
$window.location.href = path;
正如 adeneo 所指出的,原因是单击 Angular 中的按钮不会重定向。因此,必须使用 Angular 的 $window.location.href
API 手动触发。
在此答案中也可以找到一些替代方法:Using $window or $location to Redirect in AngularJS
关于javascript - 如何处理从nodejs服务器下载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40312776/