Reputation: 119
I want to download a file on button click in angularjs
<button ng-click=downloadfile()>download</button>
In controller
$scope.downloadfile=function()
{
//
}
which functionality i have to write in downloadfile function could you please explain
Upvotes: 3
Views: 6711
Reputation: 73
$scope.downloadFile = function (doc) {
var token = $localStorage.authenticationToken || $sessionStorage.authenticationToken;
if (token) {
token = 'Bearer ' + token;
}
var url = new $window.URL($location.absUrl()).origin + "/api/voyages/" +
vm.voyage.id + '/documents/' + doc.id + '?auth=' + token;
$window.open(url);
};
Upvotes: 1
Reputation: 5428
Write this out in your downloadFile()
function.
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv"; //this is an example file to download, use yours
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Upvotes: 5