Open FileStreamResult by ajax (as downloaded file)

后端 未结 2 2064
爱一瞬间的悲伤
爱一瞬间的悲伤 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();
    });
    

提交回复
热议问题