2017-06-21 20 views
0

我無法從sql server檢索或下載PDF/JPG文件。當我點擊瀏覽器中的按鈕時,它不響應,也沒有任何事情發生。請幫助我。請檢查一下,代碼是否有問題。 我有一個包含ID爲一個整數表和無法使用C#從數據庫檢索或下載PDF/JPG文件

enter image description here enter image description here

和後面的代碼:

protected void btnView_Click(object sender, EventArgs e) 
    { 
     string strQuery = "select Upload_Name, Content_Type, Uploads from Tab_CPD_Hours WHERE id [email protected]"; 
     SqlCommand cmd = new SqlCommand(strQuery); 
     cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1; 
     DataTable dt = GetData(cmd); 
     if (dt != null) 
     { 
      download(dt); 
     } 
    } 

    private void download(DataTable dt) 
    { 
     Byte[] bytes = (Byte[])dt.Rows[0]["Uploads"]; 
     Response.Buffer = true; 
     Response.Charset = ""; 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.ContentType = dt.Rows[0]["Content_Type"].ToString(); 
     Response.AddHeader("content-disposition", "attachment;filename=" 
     + dt.Rows[0]["Upload_Name"].ToString()); 
     Response.BinaryWrite(bytes); 
     Response.Flush(); 
     Response.End(); 
    } 

public static DataTable GetData(SqlCommand cmd) 
    { 
     DataTable dt = new DataTable(); 
     string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString; 
     SqlConnection con = new SqlConnection(strConnString); 
     SqlDataAdapter sda = new SqlDataAdapter(); 
     cmd.CommandType = CommandType.Text; 
     cmd.Connection = con; 
     try 
     { 
      con.Open(); 
      sda.SelectCommand = cmd; 
      sda.Fill(dt); 
      return dt; 
     } 
     catch 
     { 
      return null; 
     } 
     finally 
     { 
      con.Close(); 
      sda.Dispose(); 
      con.Dispose(); 
     } 
    } 

回答

0

它返回什麼,因爲你捕獲所有的錯誤,並返回空.. 。

catch 
{ 
    return null; 
} 

而且獲取數據的方法在null爲空時什麼也不做原來...

DataTable dt = GetData(cmd); 
if (dt != null) 
{ 
    download(dt); 
} 

您需要妥善處理錯誤,通過顯示錯誤信息給用戶...

+0

沒有錯誤,我檢查了其不獲取任何的錯誤...而調試它一直到程序結束後,什麼都沒有發生......我需要幫助:/ –

+1

你在你的aspx頁面上使用updatepanel嗎? –

+0

是的..這是我昨天解決它的原因..但非常感謝你的幫助。 :) –