2009-06-21 50 views
0

下載我試圖通過單擊鏈接,在我的網站(這是一個.doc文件,坐在我的網站服務器上)編程式下載文件。這是我的代碼:允許用戶從我的網站通過Response.WriteFile()

string File = Server.MapPath(@"filename.doc"); 
string FileName = "filename.doc"; 

if (System.IO.File.Exists(FileName)) 
{ 

    FileInfo fileInfo = new FileInfo(File); 
    long Length = fileInfo.Length; 


    Response.ContentType = "Application/msword"; 
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name); 
    Response.AddHeader("Content-Length", Length.ToString()); 
    Response.WriteFile(fileInfo.FullName); 
} 

這是在buttonclick事件處理程序中。好吧,我可以做一些關於文件路徑/文件名的代碼來使它更整潔,但是當點擊按鈕時,頁面刷新。在本地主機上,這段代碼工作正常,並允許我下載文件確定。我究竟做錯了什麼?

感謝

+0

愚蠢的問題:沒有「filename.doc」在同一地點存在於服務器上(相對於應用程序根目錄)? – Stobor 2009-06-21 22:52:27

+0

是(在根部)。 – dotnetdev 2009-06-21 23:01:28

回答

0

嘗試略加修改:

string File = Server.MapPath(@"filename.doc"); 
string FileName = "filename.doc"; 

if (System.IO.File.Exists(FileName)) 
{ 

    FileInfo fileInfo = new FileInfo(File); 


    Response.Clear(); 
    Response.ContentType = "Application/msword"; 
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name); 
    Response.WriteFile(fileInfo.FullName); 
    Response.End(); 
} 
0

哦,你不應該這樣做在按鈕單擊事件處理程序。我建議將整個事件移到HTTP處理程序(.ashx),並使用Response.Redirect或任何其他重定向方法使用戶訪問該頁面。 My answer to this question provides a sample

如果您仍想在事件處理程序中執行此操作。確保在寫出文件後進行Response.End調用。

1

而不是有一個按鈕點擊事件處理程序,你可以有一個download.aspx頁面,你可以鏈接到相反。

此頁面可以讓您的代碼在頁面加載事件。還要添加Response.Clear();在你的Response.ContentType =「Application/msword」之前;行並添加Response.End();在你的Response.WriteFile(fileInfo.FullName)之後;線。

相關問題