Open FileStreamResult by ajax (as downloaded file)

Is it possible to use an ajax call to open FileStreamResult as a downloaded file?

Controller method

public FileStreamResult DownloadPDF()
{
        var stream = myHandler.getFileStream("myfile.pdf");
        return File(stream, "application/pdf", "myfile.pdf"));
}

Html code

<a href="#" class="mydownload">Click Me</a>
<script type="text/javascript>
    $("a.mydownload").click(function () {
        $.ajax({
            method: 'GET',
            url: 'http://myserver/file/DownloadPDF',
            success: function (data, status, jqXHR) {
                var blob = new Blob([data], { type: "application/pdf" })
                var url = window.URL.createObjectURL(blob);
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.href = url;
                a.click();

            }
        });
    });
</script>

Running on IE I get access denied, but on Chrome it runs fine. I do however get a "blank"/invalid pdf.

Answers:

Answer

Use XMLHttpRequest() with responseType set to "blob", add download attribute to <a> element

$("a.mydownload").click(function () {
    var request = new XMLHttpRequest();
        request.responseType = "blob";
        request.open("GET", "http://myserver/file/DownloadPDF");
        request.onload = function() {
            var url = window.URL.createObjectURL(this.response);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = this.response.name || "download-" + $.now()
            a.click();
        }
        request.send();
});

alternatively, you can use jquery-ajax-blob-arraybuffer.js. See also Add support for HTML5 XHR v2 with responseType set to 'arraybuffer' on $.ajax

Answer

Still had issues with IE11, but a minor change to @guest271314 solutions, seems to do the trick.

  1. Set responseType after open.
  2. Use msSaveBlob on IE

$("a.mydownload").click(function() {
  var request = new XMLHttpRequest();
  request.open("GET", "http://myserver/file/DownloadPDF");
  request.responseType = "blob";
  request.onload = function() {
    var msie = window.navigator.userAgent.indexOf("MSIE");
    if (msie > 0) {
      window.navigator.msSaveBlob(this.response, "myfile.pdf");
    } else {
      var url = window.URL.createObjectURL(this.response);
      var a = document.createElement("a");
      document.body.appendChild(a);
      a.href = url;
      a.download = this.response.name || "download-" + $.now()
      a.click();
    }
  }
  request.send();
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.