.net core BS生成文件并下载到客户端

           这里是具体的调用
            var codeModelStr = new CreateModel().Create(db_table);
            WriteFiles(codeModelStr, "" + tableName, dataStr); 
            string path = AppDomain.CurrentDomain.BaseDirectory + @"\CreateCode\"; 
            //生成压缩文件(http不允许同个请求多个文件下载)
            ZipFile.CreateFromDirectory(path + dataStr, path + @"\" + dataStr + ".zip");



下方是具体方法实现

        /// <summary>
        /// 文件流写入文件
        /// </summary>
        /// <param name="codeStr"></param>
        public void WriteFiles(string codeStr, string className, string dataStr)
        {

            string path = AppDomain.CurrentDomain.BaseDirectory;

            string filePath = path + @"\CreateCode\" + dataStr;
            string fileName = className + ".cs";

            string fullFilePath = filePath + @"\" + fileName;

            //如果文件夹不存在就创建
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            if (!System.IO.File.Exists(filePath))
            {
                StreamWriter sw;
                sw = System.IO.File.CreateText(fullFilePath);
                sw.WriteLine(codeStr.ToString());
                sw.Close();
            }

        }


        /// <summary>
        /// 删除文件(包括压缩包和文件夹,客户端延时30秒调用此方法)
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult DeleteFiles(string fileName)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + @"CreateCode\" + fileName;
            string zipPath = AppDomain.CurrentDomain.BaseDirectory + @"CreateCode\" + fileName + ".zip";

            //删除压缩文件
            if (System.IO.File.Exists(zipPath))
                System.IO.File.Delete(zipPath);

            //删除文件夹
            if (Directory.Exists(filePath))
            {
                //循环删除文件夹中文件
                foreach (string d in Directory.GetFileSystemEntries(filePath))
                {
                    if (System.IO.File.Exists(d))
                    {
                        System.IO.File.Delete(d);
                    }
                }
                //删除文件夹
                Directory.Delete(filePath);
            }
            return Json(null);
        }



        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult Download(string fileName)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + @"\CreateCode\" + fileName + ".zip";
            fileName = fileName + ".zip";
            Encoding encoding;
            string outputFileName = null;
            fileName = fileName.Replace("'", "");
            string browser = Request.UserAgent.ToUpper();
            if (browser.Contains("MS") == true && browser.Contains("IE") == true)
            {
                outputFileName = HttpUtility.UrlEncode(fileName);
                encoding = Encoding.Default;
            }
            else if (browser.Contains("FIREFOX") == true)
            {
                outputFileName = fileName;
                encoding = Encoding.GetEncoding("GB2312");
            }
            else
            {
                outputFileName = HttpUtility.UrlEncode(fileName);
                encoding = Encoding.Default;
            }
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Charset = "UTF-8";
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = encoding;
            Response.AddHeader("Content-Disposition", "attachment; filename=" + outputFileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return new EmptyResult();
        }





前端部分:

            <a id="btn_download" href="" style="display:none">下载</a>

 
                 $.ajax({
                    url: '/Home/CreateGenerator',
                    async: false,
                    data: subData,
                    dataType: "json",
                    type: "post",
                    success: function (resData) {
                        //重新刷新所有样式
                        form.render();
                        layer.msg(resData.msg, { icon: resData.icon, time: 2000 });
                        if (resData.code == 200) {
                            $("#btn_download").attr("href", "/Home/Download?fileName=" + resData.data)
                            //启动下载
                            setTimeout(function () {
                                $("#btn_download")[0].click();
                            }, 500)
                            //启动删除,延时30秒执行,避免出现删除时文件没下载完成
                            setTimeout(function () {

                                $.ajax({
                                    url: '/Home/DeleteFiles',
                                    async: false,
                                    data: { fileName: resData.data },
                                    dataType: "json",
                                    type: "post",
                                    success: function (resData) {
                                       
                                    }
                                });

                            }, 10000)
                        }
                    }
                });
            


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纪寻川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值