[英]Use dynamically created link to download file in AngularJS
我正在使用ng-click调用一个函数,该函数向服务器发出一个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服务包装器。
如果我了解您,那么我想您想在动态获取链接后立即开始下载,那么您可以按照以下步骤进行操作
$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) {
}
);
}
尝试将链接保存在$ scope中。 然后,使用此:
<a target="_self" href={{your variable}} download="foo.pdf">
还要检查文档: http : //docs.angularjs.org/guide/
从这里得到的答案:
我设法使用$ window服务做到了。
ajaxRequest.ajaxPost('http://someApi.com', postData).then(
function(jsonAPI) {
link = jsonAPI.links.download;
$window.location.href = link;
},
function(errorResponse) {
}
);
只需添加$ window作为依赖项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.