0

I have a POST AJAX request in my ASP.NET MVC application, that works like this:

$.ajax({
    type: "POST",
    url: 'https://localhost:44300/api/values',
    data: ruleData,
    contentType: "application/json; charset=utf-8"
});

In this case, ruleData encompasses a JSON blob:

var ruleData = JSON.stringify({
    'TargetProduct': "SomeProduct",
    'Content': editor.getValue(),
    'TargetProductVersion' : "1.0"
});

The request is backed by a POST handled in a Web API application, that returns PushStreamContent with appropriate headers.

return new HttpResponseMessage(HttpStatusCode.OK) { Content = pushStreamContent};

In Fiddler, I see the response from the Web API coming back as application/octet-stream, in the right size as I was expecting (it generates a ZIP file in the backend), however there is never a dialog shown to allow the user to download the file.

What am I missing?

Den
  • 16,686
  • 4
  • 47
  • 87
  • Do you have anything in your controller like http://stackoverflow.com/questions/730699/how-can-i-present-a-file-for-download-from-an-mvc-controller – Jeffrey Easley Aug 31 '15 at 04:50
  • The problem is - I am using an `ApiController`, which doesn't play by the same rules as a MVC controller and does not expose the `File` returnable. – Den Aug 31 '15 at 15:41

1 Answers1

0

Solved with XHR

var xhr = new XMLHttpRequest();
                xhr.responseType = "blob";
                xhr.onreadystatechange = function(){
                    if (this.readyState == 4) {
                        if (this.status == 200)
                            {
                            download(xhr.response, "bundle.zip", "application/zip");
                        }
                        else if (this.status == 400) {
                            var reader = new FileReader();
                            reader.onload = function(e) {
                                var text = reader.result;
                                alert(text);
                            }
                            reader.readAsText(xhr.response);
                        }
                    }
                }
                xhr.open('POST', 'https://localhost:44300/api/values');
                xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
                xhr.responseType = 'blob'; // the response will be a blob and not text
                xhr.send(ruleData); 
Den
  • 16,686
  • 4
  • 47
  • 87