個人覺得要實現這個功能如果沒有類庫提供的幾個關鍵函數,還是比較繁瑣的。所以首先介紹幾個將要在代碼中使用的關鍵函數和參數,然后再說函數實現、注意問題等。
關鍵函數:
1.函數原型:Response.AppendHeader(name,value);
本例中使用: Response.AppendHeader("Content-Disposition", "attachment;filename=fileDown.doc");
說明:將http頭添加到輸出流,name 為Http頭,value為Http頭的值,可以實現刷新頁面,頁面跳轉,文件下載等,就看你name的值是什么。例如在本例中使用name為Content-Disposition:
Content-Disposition:是 MIME 協議的擴展,MIME 協議指示 MIME 用戶代理如何顯示附加的文件。當 Internet Explorer 接收到頭時,它會激活瀏覽器文 件下載對話框,它的文件名框自動填充了頭中指定的文件名,來確保瀏覽器彈出下載對話框。
在本例中value的值為attachment;filename=fileDown.doc:
attachment: attachment 參數表示作為附件下載,您可以改成 online在線打開 ,filename自定義下載的文件名稱,文件后綴為想要下載的文件類型,后面有說明。
2.Response.ContentType
本例中設置:Response.ContentType = "application/ms-word";
說明:指定文件類型 可以為application/ms-excel , application/ms-word,application/ms-txt,application/ms-html或其他瀏覽器可直接支持文檔。
3.System.Web.UI.HtmlTextWriter類
說明:將標記字符和文本寫入到 ASP.NET 服務器控件輸出流,也就是用於把HTML內容輸出到服務器控件輸出流的一個類。在本例中是將要下載的頁面內容輸出到一個StringWriter對象中。
4.RenderControl(HtmlWriter);
說明:將服務器控件的內容輸出到所提供的HtmlWriter對象中,在本例中是將要下載的頁面內容輸出到HtmlWriter中。
注意:在本例中需要將頁面的EnableEventValidation="false",<pages enableEventValidation="false"/>不然會執行出錯。
實現思想:
第一步:設置Response的格式,緩沖,編碼等,調用AppendHeader函數用於彈出瀏覽器保存文件對話框,並設置文件名字、類型以及保存方式(在線瀏覽還是作為附件保存)。
第二步:初始化HtmlWriter,將下載頁面內容輸出給HtmlWriter,並將內容輸出到一個StringWriter對象中。
第三步:將StringWriter對象的值賦值給一個string對象,然后操作字符串對象,截取想要下載的內容。
第四步:調用Response.Write將string對象輸出到第一步指定的文件中。
代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebPageContentDownload { public partial class DownloadWebPageContent : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void download_Click(object sender, EventArgs e) { //設置Http的頭信息,編碼格式 HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Charset = "gb2312"; HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); HttpContext.Current.Response.ContentType = "application/ms-word"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=fileDown.doc"); //關閉控件的視圖狀態 ,如果仍然為true,RenderControl將啟用頁的跟蹤功能,存儲與控件有關的跟蹤信息 this.EnableViewState = false; //將要下載的頁面輸出到HtmlWriter System.IO.StringWriter writer = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer); this.RenderControl(htmlWriter); //提取要輸出的內容 string pageHtml = writer.ToString(); int startIndex = pageHtml.IndexOf("<div style=\"margin: 0 auto;\" id=\"mainContent\">"); int endIndex = pageHtml.LastIndexOf("</div>"); int lenth = endIndex - startIndex; pageHtml = pageHtml.Substring(startIndex, lenth); //輸出 HttpContext.Current.Response.Write(pageHtml.ToString()); HttpContext.Current.Response.End(); } } }
