0

When I initiate a get request in angular against a webapi controller that responds with a file wrapped in an HttpResponseMessage the browser doesn't recognize that it's a file download and the data is lost.

I checked in fiddler and I can see that the binary data is present in the response.

I'm initiating the get request with this:

      return $http.get(serviceURLRoot + 'api/myreport/' + dateParams.StartDate + '/' + dateParams.EndDate, { withCredentials: true }).success(function (data) {
      });

If I type the request directly into the address bar I get the file back just fine. Using window.open also works:

window.open(serviceURLRoot + 'api/rawdatareport/' + dateParams.StartDate + '/' + dateParams.EndDate);

Why doesn't $http.get work?

EDIT -----

Here's the HttpResponseMessage as built on the server:

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(pck.GetAsByteArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
    FileName = "myReport.xlsx"
};

return result;
Legion
  • 3,922
  • 8
  • 51
  • 95
  • what are you doing with response? Ajax by itself won't iniitalize a file save dialog – charlietfl Feb 02 '17 at 20:43
  • @charlietfl I'm not sure if you mean on the server or the client. I've updated the question to show how the response is built on the server. On the client side it's just the `return $http.get` statement shown, there's nothing elided. – Legion Feb 02 '17 at 21:02

1 Answers1

0

Because you are doing an AJAX request with $http. The only way the browser is going to realize a file is coming is to have the browser go there. Realizing a file is coming, not HTML, it pops up the download. So you really have to change the location to that URL or open a new window in that URL.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • there are ways to do downloads with ajax, answer is a bit inaccurate and incomplete – charlietfl Feb 02 '17 at 20:47
  • or `window.location`, yes. You can see related answers here: http://stackoverflow.com/q/20830309/1658906 and here: http://stackoverflow.com/q/4545311/1658906. – juunas Feb 02 '17 at 21:06
  • There is also a way using an iframe used by this library: http://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js – juunas Feb 02 '17 at 21:06