Open FileStreamResult by ajax (as downloaded file)

后端 未结 2 2063
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 14:33

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

Controller method

public FileStreamResult DownloadPDF()
{
        v         


        
相关标签:
2条回答
  • 2020-12-21 14:52

    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();
    });
    
    0 讨论(0)
  • 2020-12-21 15:06

    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

    0 讨论(0)
提交回复
热议问题