1

I'm trying to download binary data using a Web API Controller, using JQuery.get().

The code I tried is:

$.get("../api/Download/Report?Id=" + selectedItem.Id);    

which transforms into an HTTP GET with this URL when I debug the running app:

http://localhost:12150/api/Download/Report?Id=2515

The browser shows 200 as result, receiving the binary data, but it does not open it nor offers to download the file. If I copy and paste the URL in the address bar and press 'Enter', it works.

Any suggestions or alternatives that allow relative paths?

2 Answers2

2

You shouldn't be using ajax for these kinds of things. If you want to force the user to download the response, that could get messy. Open a new tab/window instead; in most browsers it'll close itself anyway, and the user won't even notice that it was open! :) If you know your URLs on-load you could simply make an anchor tag with the target="_blank"-attribute. I.e.:

<a href="http://localhost:12150/api/Download/Report?Id=<?=$reportID?>" target="_blank">Download report</a>

(Well, you know basic HTML, but you get the idea)

If you want/need to do it with JS, go with a simple window.open():

window.open("../api/Download/Report?Id=" + selectedItem.Id,'_blank');

Disclaimer: I don't know if that relative URL will actually work in window.open(). If it doesn't just fiddle around with constructing the URL via PHP first:

$reportURL = $_SERVER['SERVER_NAME']."/api/Download/Report?Id=";

and then, in your JS, just echo it:

window.open("<?=$reportURL?>" + selectedItem.Id,'_blank');
rdiz
  • 6,136
  • 1
  • 29
  • 41
0

using $.get just puts the returned request data into an object you can handle in the callback. what you need to do is just have your api return the download url, then tell the browser to download it,

how to do this is explained in this answer https://stackoverflow.com/a/5192980/1994767

Community
  • 1
  • 1
Jakeii
  • 1,273
  • 9
  • 16