2012-04-12 174 views
1

這裏是我的代碼:Response.AddHeader附件不起作用

   Response.Clear(); 
       Response.AddHeader("content-disposition", "attachment; filename=file.xlsx"); 
       Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
       Response.BinaryWrite(pck.GetAsByteArray()); 
       Response.End(); 

的問題是,當這個代碼運行(On按鈕點擊)我不下載文件在我的瀏覽器(試在Chrome \ IE中)。

pck是一個excel文件(由epplus庫生成)。 我甚至不知道如何調試這部分代碼。它什麼都不做。

這裏是我得到在我的瀏覽器錯誤:

未捕獲Sys.WebForms.PageRequestManagerParserErrorException: Sys.WebForms.PageRequestManagerParserErrorException:從服務器收到的消息 無法解析。此 錯誤的常見原因是響應通過調用Response.Write(), 響應篩選器,HttpModules或服務器跟蹤已啓用而被修改時。

詳細信息:錯誤解析'PKX @π '附近。

回答

2

我相信你正在使用一個更新面板。執行異步回傳時無法下載文件。添加將下載文件的按鈕作爲更新面板的回傳觸發器。

+1

我認爲ramesh可能是對的。更新面板與管道分隔格式進行通信,該格式包含有關要更新的控件,要更新的內容等信息。修改響應時,客戶端更新面板相關代碼無法分析響應,並且出現類似於您的錯誤發佈。 – 2012-04-12 18:08:33

+0

是的,看起來像是這個問題。我能夠通過註冊回發控制來修復它:ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.button1); – user194076 2012-04-12 18:54:32

0

你在正確的軌道上。我想你錯過了幾行:

Response.Clear(); 
Response.AddHeader("content-disposition", "attachment; filename=file.xlsx"); 
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
Response.BinaryWrite(pck.GetAsByteArray()); 
Response.Flush(); 
Response.Close(); 
Response.End();