Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Angular to Download a File via Ajax

Tags:

c#

ajax

angularjs

I have a service that generates a CSV file and returns it to the page via an http/ajax get. I'd like a user to click a button, have the service get called, and then have the file get downloaded to the user's browser.

I would like to do this The Angular Way, although I recognize this may have more to do with Ajax or the browser than Anguler per se.

The service is in C#, and this is what it returns:

return File(Encoding.UTF8.GetBytes(WriteCSV(assetList)), "text/csv", "results.csv");

The controller code that calls the service looks like the following. It works, but I don't know what to do on success:

$scope.exportCSV = function () {
    $http({
        method: "get",
        url: "ExportCSV"
    }).
        error(function (data, status, headers, config) {
            alert("Error exporting data to CSV.");
        });
};
like image 396
Phil Sandler Avatar asked Mar 24 '23 13:03

Phil Sandler


1 Answers

You can't initiate a download from a normal ajax GET or POST, you have to do the traditional way, eg window.location='url' and set the correct http header with the correct content-type which will prompt the download dialog in the users browser

like image 196
Jason Jong Avatar answered Apr 01 '23 05:04

Jason Jong