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

前端开发   发布日期:2025年06月17日   浏览次数:175

这里只做一个简单的实例

  1. public ActionResult Index()
  2. {
  3. string path = Server.MapPath("/test/");//文件输出目录
  4. Encoding code = Encoding.GetEncoding("gb2312");
  5. StreamWriter sw = null;
  6. string str = "<html><body>$ShowArticle$</body></html>";//读取模版页面html代码
  7. string htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";//静态文件名
  8. // 替换内容
  9. str = str.Replace("$ShowArticle$", "你好");
  10. // 写文件
  11. try
  12. {
  13. sw = new StreamWriter(Path.Combine(path, htmlfilename), true, code);
  14. sw.Write(str);
  15. sw.Close();
  16. byte[] buffer = null;
  17. var ms = new MemoryStream();
  18. using (var file = ZipFile.Create(ms))
  19. {
  20. file.BeginUpdate();
  21. foreach (string item in Directory.GetFiles(Server.MapPath("/test")))
  22. {
  23. file.Add(Server.MapPath(Path.Combine( "test",Path.GetFileName(item))));
  24. }
  25. file.CommitUpdate();
  26. buffer = new byte[ms.Length];
  27. ms.Position = ;
  28. ms.Read(buffer, , buffer.Length);
  29. }
  30. //IE和其它浏览器都要进行UTF-8编码,中文不编码会出现乱码
  31. Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("test") + ".zip");
  32. Response.BinaryWrite(buffer);
  33. Response.Flush();
  34. Response.End();
  35. }
  36. catch (Exception ex)
  37. {
  38. return Content(ex.Message);
  39. }
  40. finally
  41. {
  42. sw.Close();
  43. }
  44. return View();
  45. }

 

以上就是.net 生成html文件后压缩成zip文件并下载的详细内容,更多关于.net 生成html文件后压缩成zip文件并下载的资料请关注九品源码其它相关文章!