标签:
开发环境:ASP.NET MVC,其他环境仅供参考。
问题描述:在开发中遇到这样的需求,保存页面,通常使用JavaScript的saveAs进行保存,各浏览器对saveAs支持,见下表。
代码一:初始保存的代码,只有IE6,7,8支持。 function CmdSave() { var OW = window.open(‘‘, "_blank", ""); var DD = new Date(); OW.document.open(); var content = document.getElementById("content").innerHTML; OW.document.write(content); var name = mineName + "-" + $("#selDate").val() + ".htm"; OW.document.execCommand("saveAs", false, name);//执行保存,IE6,IE7,IE8有效 OW.close(); }
解决方案:考虑到下载兼容性好,也能起到保存页面的作用,故采用了先生成页面,再下载页面这样的解决方案。
代码二:采用下载方式保存页面代码。 function CmdSave() { var css = "<style type=‘text/css‘>.trNormalTd { border-top-width: 0px; border-bottom-width: 0px;text-align:right;}.trLastTd {border-top-width: 0px;text-align:right;}.trFirstTd{border-bottom-width: 0px;text-align: right;}</style>"; var html = document.getElementById("content").innerHTML; var content = css + html; var name = mineName + "-" + $("#selDate").val() + ".htm"; savePage(content, name); } //content 内容 fileName 文件名 先在服务器生成页面,然后再下载生成的页面 function savePage(content, fileName) { $.ajax({ type: ‘post‘, dataType: ‘text‘, url: ‘FXBB/BCYM‘, data: { content: content, fileName: fileName }, success: function (result) { var url = "YXGZ/DBFX/BBCX/FXBB/XZYM?fileName=" + fileName; var downloadUrl = window.location.protocol + "//" + window.location.host + "/" + url; window.open(downloadUrl);//下载页面 //deleteFile(fileName); }, error: function (msg) { alert("保存出错"); } }); } //保存页面 public int BCYM(string content, string fileName) { string path = System.AppDomain.CurrentDomain.BaseDirectory; path = Path.Combine(path, @"Upload\FXBB"); //清空保存文件文件夹文件 foreach (string d in Directory.GetFileSystemEntries(path)) { if (File.Exists(d)) { File.Delete(d); } } //生成要保存的页面 path = System.AppDomain.CurrentDomain.BaseDirectory; path = Path.Combine(path, "Upload/FXBB/" + fileName); using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))// File.AppendText(path)) { sw.WriteLine(content); sw.Flush(); } return 1; } //下载页面 public void XZYM(string fileName) { string path = System.AppDomain.CurrentDomain.BaseDirectory; path = Path.Combine(path, @"Upload\FXBB\" + fileName); string filePath = path;//Server.MapPath("DownLoad/aaa.zip");//路径 //以字符流的形式下载文件 FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); System.Web.HttpContext.Current.Response.WriteFile(filePath); }
JS中用execCommand("SaveAs")保存页面兼容性问题解决方案
标签:
原文地址:http://www.cnblogs.com/wllzbky/p/4889142.html