2010-12-22 43 views
0

我有這樣的代碼中插入從數據庫中的圖像控制圖片:當我嘗試插入圖片從數據庫到控制 - 我得到保存圖片在磁盤

string strQuery = "select Pic from MEN where id='1'"; 
SqlCommand cmd = new SqlCommand(strQuery); 
Convert.ToInt32(Request.QueryString["ImageID"]); 
cmd.Parameters.Add("1", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]); 
DataTable dt = GetData(cmd); 

if (dt != null) 
{ 
    Byte[] bytes = (Byte[])dt.Rows[0]["Pic"]; 
    Response.Buffer = true; 
    Response.Charset = ""; 
    Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    //Response.ContentType = dt.Rows[0]["ContentType"].ToString(); 
    Response.ContentType = dt.Rows[0]["PIC"].ToString(); 
    Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["PIC"].ToString()); 
    Response.BinaryWrite(bytes); 
    Response.Flush(); 
    Response.End(); 
} 

這:

private DataTable GetData(SqlCommand cmd) 
{ 
    DataTable dt = new DataTable(); 
    String strConnString = "server=" + Server + ";database=" + DataBase + ";UID=" + UID + ";password=" + PASS + ";"; 

    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(); 
    } 
} 

和這一形象:

<asp:image ID="Image2" runat="server" ImageUrl ="PhoneBook.aspx?ImageID=1"/> 

但是當我運行這段代碼,我得到「保存在磁盤上的圖片」,而不是插入的圖像控制

如何解決?

感謝

+0

什麼內容類型的樣子在瀏覽器? – 2010-12-22 11:16:29

回答

1

嘗試刪除:

Response.AddHeader("content-disposition", "attachment;filename="+dt.Rows[0]["PIC"].ToString()); 

還設置了Response.ContentType到MIME類型的圖像,而不是文件名。 (這裏是MIME類型的列表:http://www.w3schools.com/media/media_mimeref.asp) ,然後告訴我們,如果它的工作原理

另一種選擇是創建一個asp.net處理程序(ashx的),而不是一個aspx頁面。

樣品在這裏:http://msdn.microsoft.com/en-us/library/ms972953.aspx 這裏:http://aspalliance.com/1322_Displaying_Images_in_ASPNET_Using_HttpHandlers.all

+0

感謝您的幫助,我刪除了你寫給我的信息。但如何做到這一點:將Response.ContentType設置爲圖像的MIME類型,而不是文件名。 ?我可以取樣嗎? – Gold 2010-12-22 11:26:55

相關問題