我正在尝试使用节点js从远程URL下载文件并将文件发送到浏览器。响应返回到我的前端代码后,我想自动下载它。有人可以帮忙吗?这是我的代码片段:
Backend node js code I am using request to make the remote url call:
var request = require('request');
var config = req.param('config');
res.setHeader("content-disposition", "attachment; filename=" + config.fileName);
request('http://' + config.hostname + ':' + config.port + config.path).pipe(res);
Front end code in angular 1.5x:
var config = {
hostname: APP_CONFIG.API_HOST,
port: APP_CONFIG.API_PORT,
path: '/document,
method: 'GET',
fileName: row.Name,
fileType: row.Type
};
$http.put('/getFileFromUrl', {
config: config
})
.then(function onSuccess(res) {
if (res.data !== null && res.data.error === undefined) {
// .........what should I do here its not auto downloading
if (APP_VARS.isLoader === true) {
APP_VARS.isLoader = false;
grxUI.loading.stop();
}
}
})
答案 0 :(得分:0)
这是一个 Download 按钮的示例,该按钮在从服务器加载数据后变为活动:
<a download="data_{{files[0].name}}" xd-href="data">
<button ng-disabled="!data">Download</button>
</a>
xdHref
指令
app.module("myApp").directive("xdHref", function() {
return function linkFn (scope, elem, attrs) {
scope.$watch(attrs.xdHref, function(newVal) {
if (newVal) {
elem.attr("href", newVal);
}
});
};
});
下载二进制文件时,设置XHR的responseType
属性非常重要。
var config = { responseType: 'blob' }
var httpPromise = $http.get(url, config);
httpPromise.then(function (response) {
$scope.data = response.data;
});
有关详细信息,请参阅MDN XHR API - ResponseType.