ajax文件下载

一、Jq扩展方法

$.extend({
    downloadFile: function (reqType, url, dataOptions) {

        var dataObj = null;
        if (typeof (dataOptions) == "object") {
            dataObj = JSON.stringify(dataOptions);
        } else {
            dataObj = dataOptions;
        }

        var xmr = null;
        if (window.XMLHttpRequest) {// code for all new browsers
            xmr = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {// code for IE5 and IE6
            xmr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xmr == null) {
            alert("当前浏览器版本过低,不支持文件下载");
            return;
        }
        xmr.open(reqType, url, true);
        if (reqType.toLowerCase() == "post") {
            xmr.setRequestHeader("Content-Type", "application/json");
        }
        xmr.setRequestHeader("Authorization", "Bearer " + $.cookie("BtYinLong"));

        xmr.responseType = 'blob';
        xmr.onload = function (res) {
            if (xmr.status === 200) {
                var blob = new Blob([xmr.response]);
                var dispositionArray = xmr.getResponseHeader("Content-disposition").split(";");
                var filename = dispositionArray[dispositionArray.length - 1].replace("filename*=UTF-8''", '').replace(" ", '');
                filename = decodeURI(filename);

                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, filename);
                } else {
                    var csvUrl = URL.createObjectURL(blob);
                    var link = document.createElement('a');
                    link.href = csvUrl;
                    link.download = filename;
                    link.click();
                }
            } else {
                alert(xmr.status + ' ' + xmr.statusText);
            }
        };
        xmr.send(dataObj);

    }
})

二、调用示例:$.downloadFile("post",url,{id:1});

三、.netcore Api后端返回实列:

        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
       
        public IActionResult ExportUrgeRecord(PreUrgeRecordQuery dto)
        {
            var data = pre_UrgeRecordRepository.GetList(dto).Result;
            var bytes = ExportExcelHelper.GenExcelFileStream(data.rows);
            return File(bytes, "application/octet-stream", "记录导出列表.xlsx");
            
        }

 

posted @ 2020-06-11 17:51  潇潇与偕  阅读(1150)  评论(0编辑  收藏  举报