ajax实现文件下载

javascript 代码

        function downloadFile() {
            $.ajax({
                type: "get",
                async: false,
                url: '@Href("~/dataStandard/ServerExportMDBFile")',
                data: "",
                success: function (dataUrl) {//dataUrl tempFile/xxx.mdb
            
var urlArray = window.location.href.split("/");
            //urlArray[0]->http urlArray[2]->域名:192.168.0.66 urlArray[3]->Test
var fileUrl = urlArray[0] + "//" + urlArray[2] + "/" + urlArray[3] + "/" + dataUrl;
            //通过window.open(urlAddess) 直接打开js拼接出来的 js window.open(fileUrl); }, error:
function (url) { alert("错误:" + url); } }) }

C# 代码

        public string ExportMDBFile()
        {
            Random random = new Random();

            string relativeServerPath = Server.MapPath("../");
            string relativePath = @"ConfigDataStandard.mdb";
            string filePath = Path.Combine(relativeServerPath, relativePath);

            // DS + 日期 + 0-9999随机数
            string relativeGoalPath = @"tempFileDS" + DateTime.Now.ToString("yyyyMMdd") + random.Next(0, 9999).ToString() + ".mdb";
            string goalPath = Path.Combine(relativeServerPath, relativeGoalPath);

            // 复制文件到指定路径
            System.IO.File.Copy(filePath, goalPath);
            //初始化 OnStr
            shwyTabObject.Configuation.Init(goalPath);

            List<lirObjModel.Boj_SYS_CODE> codeList = null;
            List<lirObjModel.Boj_SYS_TYPE> typeList = null;

            using (lirObj.BojModelsVisitor visitor = new lirObj.BojModelsVisitor())
            {
                codeList = lirObjModel.Boj_SYS_CODE.List(visitor);
                typeList = lirObjModel.Boj_SYS_TYPE.List(visitor);
            }

            using (shwyObj.BojModelsVisitor visitor = new shwyObj.BojModelsVisitor())
            {
                foreach (var item in codeList)
                {
                    shwyObj.BOJModels.Boj_SYS_CODE code = shwyObj.BOJModels.Boj_SYS_CODE.Create();
                    code.Code = item.Code;
                    code.Id = item.Id;
                    code.Name = item.Name;
                    code.Title = item.Title;
                    code.Typeid = item.Typeid;

                    shwyObj.BOJModels.Boj_SYS_CODE.Insert(visitor, code);
                }

                foreach (var item in typeList)
                {
                    shwyObj.BOJModels.Boj_SYS_TYPE type = shwyObj.BOJModels.Boj_SYS_TYPE.Create();
                    type.ID = item.ID;
                    type.NAME = item.NAME;

                    shwyObj.BOJModels.Boj_SYS_TYPE.Insert(visitor, type);
                }
            }
            //第一个 Replace 替换 文件呢绝对路径为相对路径 第二个 Replace 将 \ 替换为 /
            return goalPath.Replace(relativeServerPath, "").Replace("\", "/");
        }
View Code
原文地址:https://www.cnblogs.com/yy981420974/p/8193288.html