由AngularJS从node.js中的非公共目录下载文件

时间:2014-11-10 09:16:56

标签: angularjs node.js download

我已经阅读了很多答案尝试了许多片段,但我无法解决我的问题。

我在使用快速框架的node.js编写的Angular和后端应用程序中创建了一个Web应用程序。

用户可以将文件上传到该应用程序,此文件保存在公共场所无法使用的目录中。

该应用程序的另一个功能是可以按用户下载上传的文件。在这里我的问题开始了。

我将从前端应用程序和后端显示一些代码。

控制器:

$scope.getAttachment = function (fileName) {
    return attachmentService.getAttachment({
            fileName: fileName
        }).then(function (data, status, headers, config) {
            var element = angular.element('<a/>');
            element.attr({
                href: 'data:application/pdf,' + encodeURIComponent(data),
                target: '_blank',
                download: fileName
            })[0].click();
        });
    };

服务:

getAttachment: function (req) {
    return $http.get('/attachment/' + req.fileName);
}

首先,有没有办法获取有关请求的文件mime类型的信息?所有这些参数statusheadersconfig都未定义。

后端:

function (req, res) {
    logger.trace('Getting attachment ' + req.param('fileName'));
    async.waterfall([
            function (cb) {
                attachmentService.getAttachment(req.param('fileName'), cb);
            }
        ], function (err, filePath) {
            if (err) {
                logger.error(util.inspect(err));
                res.status(404).json({message: err.code});
            } else {
                res.status(200).attachment(filePath).sendFile(filePath, {
                    root: path.join(__dirname, '..', '..')
                });
            }
        }
    );
});

此解决方案适用于TXT文件,但图像已损坏(无法打开),PDF无内容但可以打开。

以下是回复标题:

Accept-Ranges:bytes
Cache-Control:public, max-age=0
Connection:keep-alive
Date:Mon, 10 Nov 2014 10:19:13 GMT
ETag:W/"1a-3292258531"
Last-Modified:Mon, 10 Nov 2014 09:57:26 GMT
X-Powered-By:Express

我已经将后端实现更改为使用来自快速框架的res.download方法:

res.download(filePath, req.param('fileName'), function (err) {
    if (err) {

    }
});

之后我注意到错误被抛出,标题为“Request aborted”,代码为“ECONNABORT”。为什么呢?

0 个答案:

没有答案