【问题标题】:How to handle downloads of an image from a nodejs server?如何处理从 nodejs 服务器下载的图像?
【发布时间】:2017-03-11 19:12:45
【问题描述】:

我目前正在学习 node.js,最近遇到了一种情况,我想通过单击网页上的按钮下载存储在服务器上的图像。我创建了一个端点,控制器将两个参数传递给该端点:
- 要下载的图片名称(目录固定)
- 下载图片的名称

我已经尝试了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>

这是我的控制器:

$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),但结果相同。

我的方法是使用控制器内部的回调来处理这个问题。但我不知道该怎么做。我错过了什么/做错了什么?有人可以指出我正确的方向吗?

提前谢谢你。

【问题讨论】:

  • 如果你使用 Express,你应该可以只做res.download('image_dump/OutputDump/' + req.params.imageName)
  • @adeneo,我试过了。但没有运气。没有下载对话框。我的默认下载目录中也不存在文件。
  • 如果您只是在浏览器中输入 URL,它会开始下载吗?按钮通常不会重定向,Angular 也不会?
  • 哎哟。那成功了!非常感谢!

标签: javascript node.js file express download


【解决方案1】:

为了完整起见,以下是我解决问题的方法:
在我的控制器中,而不是使用:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    相关资源
    最近更新 更多