.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(); }