.net core MVC 下载文件

之前写的下载,在.net core下不能用了,所以重新写了一下。

js代码

function DataExport(URL,data,newName) {
    $.ajax({
        type: 'POST',
        url: URL,
        //contentType: "application/json; charset=utf-8",
        data: data,
        async: false,
        success: function (result) {
            console.log(result);
            setTimeout(function () {
                //异常判断与处理
                if (result.errorCode) {
                    //$.dialog.alert("查询失败。错误码:"+result.errorCode);
                    return;
                }
                console.log(result);

                window.location.href = '/BaseData/Download?fileName=' + result + '&NewName=' + newName

            }, 200);

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //$.dialog.alert("查询失败");
            //$wrapper.spinModal(false);
        }
    });
}

controller层代码

        [HttpGet]
        public IActionResult Download(string fileName, string NewName = "")
        {
            var addrUrl = fileName;
            var stream = System.IO.File.OpenRead(addrUrl); //Path.GetExtension
            string fileExt = Path.GetExtension(fileName);
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi = provider.Mappings[fileExt];
           // var downloadName = Path.GetFileName(addrUrl);
            return File(stream, memi, NewName + "Data.xlsx");

           // return File(fileName, "application/vnd.ms-excel", NewName + "Data.xlsx");
        }

 

你可能感兴趣的:(.net,core,MVC)