Ajax异步请求返回文件流(eg:导出文件时,直接将导出数据用文件流的形式返回客户端供客户下载)

在异步请求中要返回文件流,不能使用JQuery,因为$.ajax,$.post 不支持返回二进制文件流的类型,可以看到下图,dataType只支持xml,json,script,html这几种格式,没有blob类型。所以只能选择使用原生Ajax XMLReques对象进行处理

前端代码

function output() {
            var branchCode = $("#currentBranchCode").val();
            var transDate = $("#currentTransDate").val();
            if (branchCode == "" || transDate == "") {
                layer.msg("暂无记录,无法导出", { icon: 7, time: 1000 });
                return;
            }
            var fileName = $("table caption").html() + ".xls";//设置下载时候的文件名
            //要请求的Url和携带的参数
            var url = "/SellAnalyze/Export?currentBranchCode=" + branchCode + "&currentTransDate=" + transDate;
            var xhr = new XMLHttpRequest();
            //设置响应类型为blob类型
            xhr.responseType = "blob";
            xhr.onload = function () {
                if (this.status == "200") {
            //获取响应文件流  
var blob = this.response; var aElem = document.getElementById("exportUrl");
            //将文件流保存到a标签 aElem.href
= window.URL.createObjectURL(blob); aElem.download = fileName; aElem.onload = function (e) { window.URL.revokeObjectURL(aElem.href); }; $("#exportUrl").removeClass("hidden"); layer.confirm('文件已导出, 立即下载?', function (index) { $("#download").click(); layer.close(index); }); } } xhr.open("post", url, true); xhr.send(); }

后端代码

     public ActionResult Export(int? currentBranchCode, DateTime currentTransDate)
        {
            MemoryStream ms = NPOIExcelWrite(datas);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel");
        }
        
        /// <param name="datas">写入的数据</param>
        /// <returns></returns>
        private MemoryStream NPOIExcelWrite(SellDTO[] datas)
        {
            string[] titles = { "货品类别", "货品类别描述", "销售额", "同比", "环比" };
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
            NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
            for (int i = 0; i < titles.Length; i++)
            {
                row.CreateCell(i).SetCellValue(titles[i]);
            }
            for (int i = 0; i < datas.Length; i++)
            {
                row = sheet.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(datas[i].JewelryType);
                row.CreateCell(1).SetCellValue(datas[i].JewelryTypeDesc);
                row.CreateCell(2).SetCellValue(datas[i].CurrentMonthSaleroom.ToString("F2"));
                row.CreateCell(3).SetCellValue(datas[i].YearOverYear);
                row.CreateCell(4).SetCellValue(datas[i].LinkRelative);
            }

            MemoryStream ms = new MemoryStream();
            book.Write(ms);
            ms.Flush();
            book = null;
            return ms;
        }

 参考:https://blog.csdn.net/swl979623074/article/details/77855629/

https://www.cnblogs.com/cdemo/p/5225848.html

https://blog.csdn.net/fangchen12312/article/details/55271296

原文地址:https://www.cnblogs.com/c-supreme/p/9765648.html