本文针对ASP.NET MVC环境下execCommand保存页面在不同浏览器中支持度不一的问题,提出了一种基于生成的替代方案。通过先生成页面内容再触发下载的方式,有效解决了IE6-8以外的浏览器兼容性问题,提供了更稳定的页面保存实现路径。
ASP.NET MVC中execCommand兼容性问题及解决方案
本方案主要面向ASP.NET MVC开发环境,其他开发环境的开发者可参考此思路。
问题描述:在开发过程中,我们常遇到需要保存页面的需求。通常的做法是使用JavaScript的saveAs方法,但各浏览器对该方法的支持情况存在差异,具体表现见下表。

代码一:初始保存代码仅支持IE6、IE7和IE8浏览器。
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);
}
以上内容即为关于execCommand兼容性问题的完整叙述,希望对大家有所帮助。