2016-09-22 45 views
0

我在ASP.NET中創建了一個用於從我的數據庫下載文件的腳本。當我點擊下載按鈕時,加載下載的文件是帶有我的下載按鈕的頁面名稱的標題,並且該文件保存爲.aspx文件而不是.docx,因爲它最初在我上傳時保存。ASP.NET下載腳本正在加載當前頁面文件作爲下載文件

請幫助我解決這個問題。

protected void Download(object sender, EventArgs e) 
{ 
    if (Request.QueryString["Request-Id"] != "") 
    { 
     string fileName = getFileName(Convert.ToInt32(Request.QueryString["Request-Id"])); 

     if (fileName != "") { 
      Response.ContentType = "Application/vnd.openxmlformats-officedocument.wordprocessingml.document"; 
      Response.AppendHeader("content-deposition", "attachment/filename=\""+fileName+"\""); 
      Response.TransmitFile(Server.MapPath("/Uploads/" + fileName)); 
      Response.End(); 
     } 
    } 
} 

protected string getFileName(int id) 
{ 
    string connStr = ConfigurationManager.ConnectionStrings["DbCall"].ToString(); 
    SqlConnection conn = new SqlConnection(connStr); 

    conn.Open(); 
    SqlCommand command = new SqlCommand("select Conveyance_Document from Convey where Request_Id = @Id", conn); 
    command.Parameters.AddWithValue("@Id", Convert.ToInt32(id)); 

    SqlDataReader sdr = command.ExecuteReader(); 

    if (sdr.Read()) 
    { 
     string fileName = sdr["Conveyance_Document"].ToString(); 
     conn.Close(); 
     conn.Dispose(); 
     return fileName; 
    } 
    else 
    { 
     conn.Close(); 
     conn.Dispose(); 
     return ""; 
    } 
} 
+2

*尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現問題所需的最短代碼。沒有明確問題陳述的問題對其他讀者沒有用*見[mcve] –

+0

這個問題可能已經很容易回答了,因爲它已經被問*很多*次http://stackoverflow.com/search?q=how+到+下載+文件+ asp.net –

回答

0

試試這個:

Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; 
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); 
Response.TransmitFile(Server.MapPath("/Uploads/" + fileName)); 
Response.End(); 

的頭名是Content-Disposition,不content-deposition

+0

非常感謝,它工作正常。請你能幫我別的東西請 –

+0

是的,我會盡力幫助你。但請確認我的答案,因爲它解決了您的問題。如果您有其他問題,請添加另一個問題。 – krlzlx

+0

請我需要一個在asp.net中的web服務,它將在我的應用程序的後臺運行,以檢查用戶的響應。這是怎麼回事。當有人輸入日誌時,日誌需要來自特定部門的響應。所以我需要做一個背景檢查,看看日誌是否已被部門回覆。如果不是24小時後,我將不得不發送電子郵件到另一個部門,提醒他們回覆。我的問題是我不知道如何創建後臺服務來做檢查。 –