我有一个Angular应用程序,我想在有人点击链接时触发文件下载(XML)。该链接实际上是在后端调用REST端点,然后端点返回需要下载的文件。所有这一切都需要通过发送我已在代码中编码的HTTP头来完成。但我不太清楚如何在这里做到这一点。这是我的代码:
<table class="footable table table-stripped toggle-arrow-tiny" data-page-size="8" ng-if="vm.deliveries.length!=0">
<thead>
<tr>
<th>Release Slug</th>
<th>Status</th>
<th>Delivery XML</th>
<th>Retry</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="delivery in vm.deliveries" footable>
<td>{{delivery.slug}}</td>
<td>{{delivery.data.status}}</td>
<td align="center">
<a target="_self"
href="{{config.apiUrl}}/deliveries/{{delivery.slug}}/ddex"
tooltip="Download" ng-click="vm.getDeliveryDdex(delivery.slug)"><i class="fa fa-download"/></a>
</td>
<td><a ng-click="vm.downloadXML(delivery.slug)" ng-if="delivery.data.status=='FAILED'">
<i class="fa fa-repeat"></i></a></td>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<ul class="pagination pull-right"></ul>
</td>
</tr>
</tfoot>
</table>
当我点击&#34; Delivery XML&#34;时,我有一个ng-click方法&#34; vm.downloadXML&#34;在我的JS文件中看起来像这样:
function DeliveriesController(deliveriesService){
var vm = this;
vm.deliveries = {};
vm.downloadXML = downloadXML;
function downloadXML(releaseSlug){
var url = APP_CONFIG.apiUrl + '/deliveries/' + releaseSlug + '/xml';
var expectedMediaType = 'xml';
var headers = {'User-Id':'abc','User-Name':'ABC XYZ', 'Workspace':'abc', 'Content-Type': 'application/xml', 'Accept': expectedMediaType};
$http.get(url,{
headers: headers
}).then(function (response){
console.log(response);
});
}
我不确定如何在我的代码中的$ http.get调用之后处理。任何建议
答案 0 :(得分:1)
您可以附加<a>
标记,将文件网址设置为href属性并触发单击以下载文件。检查下面的代码,
function DeliveriesController(deliveriesService){
var vm = this;
vm.deliveries = {};
vm.downloadXML = downloadXML;
function downloadXML(releaseSlug){
var url = APP_CONFIG.apiUrl + '/deliveries/' + releaseSlug + '/xml';
var expectedMediaType = 'xml';
var headers = {'User-Id':'abc','User-Name':'ABC XYZ', 'Workspace':'abc', 'Content-Type': 'application/xml', 'Accept': expectedMediaType};
$http.get(url,{
headers: headers
}).then(function (response){
console.log(response);
//=== add <a> tag and trigger click ===
var link = document.createElement('a');
link.addEventListener('click', function(ev) {
link.href = response.url; // url of the file to be downloaded
link.download = "name";
document.body.removeChild(link);
}, false);
document.body.appendChild(link);
link.click();
});
}