MVC返回数据流,ajax接受并保存文件

js代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="Scripts/jquery-3.3.1.js"></script>
    <script>

        function download() {
            var url = '/Order/DownloadResource?o=90&t=bf32a13f4701473a9385896f5578953d';
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);        // 也可以使用POST方式,根据接口
            xhr.responseType = "blob";    // 返回类型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) {
                        var a = document.createElement('a');
                        a.download = 'data.rar';//下载文件名
                        a.href = e.target.result;
                        $("body").append(a);    // 修复firefox中无法触发click
                        a.click();
                        $(a).remove();
                    }
                }
            };
            // 发送ajax请求

            xhr.send()

        }
    </script>
</head>
<body>
    <input type="button" value="下载" onclick="download()" />
</body>
</html>

后台代码

        [HttpPost]
        public void Download(string o, string t)
        {
            string filePath = @"D:Download排期(20190412).xlsx";

            #region 处理下文件
            var arr= filePath.Split('\');
            string fileName = arr[arr.Length-1];
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            if (fileInfo.Exists == true)
            {
                const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
                byte[] buffer = new byte[ChunkSize];

                Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
                while (dataLengthToRead > 0 && Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
                    Response.OutputStream.Write(buffer, 0, lengthRead);
                    Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                Response.Close();
                Response.End();
            }
            #endregion
        }
原文地址:https://www.cnblogs.com/zhuyapeng/p/10796664.html