ljacquet
ljacquet

Reputation: 29

Requesting XLSX file through js to authorized asp.net web api

I have ajax calling my web api to get a xlsx file that is generated when it is called. The xlsx file is in a memory stream that I know is correct because I downloaded it straight from the server and had no issue. However when I try to download the file through the browser it says that the file is invalid. I'm using downloadjs to download the data.

How I return the Stream

 public HttpResponseMessage Function_Name() {
        var stream = getStream();

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }

How I get the Stream

$.ajax({ url: "urlToData", headers: {
                'Authorization': 'Authorization'
            },
         success: function (data) { download(data, "test.xlsx"); } 
});

When I run this code I get a file however that file does not read in excel. The file is also 15.3 KB where the functioning file downloaded straight from the server is actually 10.0kb

Upvotes: 1

Views: 66

Answers (1)

ljacquet
ljacquet

Reputation: 29

I was feeling desperate and tried this out: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/

When I used XMLHttpRequest() it worked correctly.

var xhr = new XMLHttpRequest()

xhr.open('GET', 'url', true);
xhr.setRequestHeader('Authorization', 'Authorization');
xhr.responseType = 'blob';

xhr.onload = function(e) {
    if(this.status == 200) {
        var blob = this.response;
        download(this.response, "test.xlsx")
    }
}

xhr.send();

Upvotes: 1

Related Questions