• .net 生成html文件后压缩成zip文件并下载


    这里只做一个简单的实例

     public ActionResult Index()
            {
    
                string path = Server.MapPath("/test/");//文件输出目录
    
                Encoding code = Encoding.GetEncoding("gb2312");
    
                StreamWriter sw = null;
    
                string str = "<html><body>$ShowArticle$</body></html>";//读取模版页面html代码
    
                string htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";//静态文件名
    
                // 替换内容
    
                str = str.Replace("$ShowArticle$", "你好");
    
                // 写文件
                try
                {
                    sw = new StreamWriter(Path.Combine(path, htmlfilename), true, code);
                    sw.Write(str);
                    sw.Close();
                    byte[] buffer = null;
                    var ms = new MemoryStream();
                    using (var file = ZipFile.Create(ms))
                    {
                        file.BeginUpdate();
                        foreach (string item in Directory.GetFiles(Server.MapPath("/test")))
                        {
                            file.Add(Server.MapPath(Path.Combine( "test",Path.GetFileName(item))));
                        }
    
                        file.CommitUpdate();
    
                        buffer = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(buffer, 0, buffer.Length);
                    }
    
                    //IE和其它浏览器都要进行UTF-8编码,中文不编码会出现乱码
    
                    Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("test") + ".zip");
                    Response.BinaryWrite(buffer);
                    Response.Flush();
                    Response.End();
                }
                catch (Exception ex)
                {
                    return Content(ex.Message);
                }
    
                finally
                {
                    sw.Close();
                }
                return View();
            }
  • 相关阅读:
    1.saltstack入门
    构造函数
    gitlab
    mysql常见的问题
    python数据运算
    BZOJ 1691 usaco2007 挑剔的美食家
    BZOJ 1708 usaco2007 Money奶牛的硬币
    BZOJ 1050 HAOI2006 旅行comf
    BZOJ 2427 HAOI2010 软件安装
    BZOJ 1901 Dynamic Rankings
  • 原文地址:https://www.cnblogs.com/lunawzh/p/10211830.html
Copyright © 2020-2023  润新知