Javascript前端请求后端Asp.Net MVC 文件流到前端通知浏览器下载

 前端请求代码:

   


<script>

$("#btn1").click(function () {
           
                var downloadFile = function () { download("设置文件名称.docx", "DownFile?Id=" + Id); };
             
                downloadFile();
          
        });


function download(fileName, url) {
            //要请求的Url和携带的参数
            var xhr = new XMLHttpRequest();
            //设置响应类型为blob类型
            xhr.responseType = "blob";
            xhr.onload = function () {
                if (this.status === 200) {
                    // 请求完成
                    var blob = this.response;
                    var reader = new FileReader();
                    reader.readAsDataURL(blob);    // 转换为base64,可以直接放入a表情href
                    reader.onload = function (e) {
                        // 转换完成,创建一个a标签用于下载
                        var a = document.createElement('a');
                        a.download = fileName;
                        a.href = e.target.result;
                        $("body").append(a);    // 修复firefox中无法触发click
                        a.click();
                        $(a).remove();
                    }
                }
            };
            xhr.open("post", url, true);
            xhr.send();
        }


</script>

后端文件生成代码:

  public FileResult DownFile(string Id)
        {
            byte[] bytes = null;
            return File(bytes, "application/octet-stream", "设置文件名称.docx");
        }
发布了60 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_24432127/article/details/93751324