Open FileStreamResult by ajax (as downloaded file)

2020-04-19 06:37发布

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.

2条回答
够拽才男人
2楼-- · 2020-04-19 06:56

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

查看更多
▲ chillily
3楼-- · 2020-04-19 07:07

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();
});
查看更多
登录 后发表回答