2012年7月31日 星期二

iframe實作Download功能,保持頁面程序完全執行完畢

所以若想要提供Download功能,又期望原本的頁面其它後續要處理的事件能完整執行
這部份我們可以利用 iframe 做個小技巧的轉彎,直接來看實作

  • 在頁面藏一個iframe ,並設置其style為隱藏
1<iframe id="dlframe" runat="server" style="display: none"></iframe>
  • 利用泛型處理常式(.ashx)背後處理Download的行為
01public void ProcessRequest(HttpContext context)
02{
03    
04   //前面程式碼省略.......
05    context.Response.ContentType = "Application/save-as";
06    context.Response.Charset = "utf-8";
07    //透過Header設定檔名
08    context.Response.AddHeader("Content-Disposition", "Attachment; filename=" + HttpUtility.UrlEncode(filename));
09    context.Response.BinaryWrite(Buf);
10    context.Response.End();
11}
  • 原本頁面的Button 事件,把 iframe 的 src 屬性指向泛型處理常式(.ashx)
1protected void Button1_Click(object sender, EventArgs e)
2{
3    this.dlframe.Attributes.Add("src", "Download.ashx");
4     
5    //頁面顯示時間
6    Response.Write(DateTime.Now.ToString());
7}

這樣的一個方式就形成了把 Download的 request 行為交由另一個頁面來進行,也就避開了
Response.End 的影響,因此頁面顯示時間的程式碼部份也會正常的被執行






沒有留言:

張貼留言