我正在使用ng-click调用一个函数,该函数向服务器发出一个post http请求,然后创建一个链接。如何使用此创建的链接同时下载附加到其中的文件?
我的模板
<button ng-click="getFile(row)">Download</button>
我的控制器
$scope.getFile = function(row){
row.isSelected = true;
var link = null;
var postData = {
"data" : {
"type": "member_report",
"relationships": {
"member" : {
"data": {
"type": "user",
"id": memberID
}
}
}
}
}
ajaxRequest.ajaxPost('http://someApi.com', postData).then(
function(jsonAPI) {
link = jsonAPI.links.download; //here is the response link
//todo something with it to download file
},
function(errorResponse) {
}
);
}
顺便说一下,ajaxRequest只是一个简单的$ http服务包装器。
答案 0 :(得分:1)
如果我理解你,那么我想你想在动态获得链接后立即开始下载,然后你可以按照以下步骤进行操作
$scope.getFile = function(row){
row.isSelected = true;
var link = null;
var postData = {
"data" : {
"type": "member_report",
"relationships": {
"member" : {
"data": {
"type": "user",
"id": memberID
}
}
}
}
}
ajaxRequest.ajaxPost('http://someApi.com', postData).then(
function(jsonAPI) {
link = jsonAPI.links.download;
// Now we want to download the link
var downloadLink = document.createElement('a');
downloadLink .href = link;
// now set the visibility to hidden so that it doesnt effect the frontend layout
downloadLink .style = 'visibility:hidden';
downloadLink .download = 'file_name';
// now append it to the document, generate click and remove the link
document.body.appendChild(downloadLink );
downloadLink .click();
document.body.removeChild(downloadLink );
},
function(errorResponse) {
}
);
}
答案 1 :(得分:0)
尝试将链接保存在$ scope中。然后,使用:
<a target="_self" href={{your variable}} download="foo.pdf">
另请查看文档: http://docs.angularjs.org/guide/
从这里回答:
How do you serve a file for download with AngularJS or Javascript?
答案 2 :(得分:0)
我设法使用$ window服务。
ajaxRequest.ajaxPost('http://someApi.com', postData).then(
function(jsonAPI) {
link = jsonAPI.links.download;
$window.location.href = link;
},
function(errorResponse) {
}
);
只需添加$ window作为依赖