Matt Cashatt
Matt Cashatt

Reputation: 24218

Using AngularJS or just JavaScript, how do I download a file via ajax?

Background

I am developing a web application in which an authenticated user may create an event and send out invitations to that event.

One of the requirements is that I add a button, which the event organizer can click to allow him/her to download an excel/OOXML report of all invitations sent.

Architecture

The view and actual button-click event all live in a "Web" project which runs on ASP.NET MVC 4 and is using mostly plain HTML and AngularJs as a platform.

I also have an API project supported by a BLL, DAL, etc. The API is .NET MVC WebAPI and it is the provider of the spreadsheet via this endpoint:

/// <summary>GET api/ExportInvitations/{id}</summary>
/// <summary>Gets an OOXML invitation report by event id.</summary>
public HttpResponseMessage Get(int id)
{
    var wb = Invitation.ConstructInvitationSpreadsheet(id);

    var result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new MemoryStream(); 
    wb.SaveAs(stream);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "HelloWorld.xlsx" };
    return result;

}

On the front end, I am using this AngularJS scripting to call the API endpoint that constructs and returns the spreadsheet (I have summarized this code for the sake of brevity):

 $http.get('/api/ExportInvitations/' + id).success(function(data) {
                    //do stuff
                });

The Problem

Everything seems to work well up to the point that the user should see the spreadsheet appear in their browser as a download. The ajax call to the API is fine, and the API returns a spreadsheet as it should--I just never see the file appear as a download at the bottom of my browser (I am using Chrome).

Any help is appreciated.

Upvotes: 0

Views: 1647

Answers (1)

Matt Cashatt
Matt Cashatt

Reputation: 24218

I found the answer in another SO post shortly after posting this:

You can't download via ajax per se, you just need to reset the location of the window. So, instead of this:

 $http.get('/api/ExportInvitations/' + id).success(function(data) {
                    //do stuff
                });

I just need this:

window.location = '/api/ExportInvitations/' + id;

And this triggers the download without actually changing the URL in the browser.

Upvotes: 3

Related Questions