读书人

从数据库读取二进制图片写出来是个叉叉

发布时间: 2011-12-18 22:54:38 作者: rapoo

从数据库读取二进制图片写出来是个叉叉````急``搞了好久了```
我的代码如下```

private void WriteFrom(string id)
{
OleDbConnection conn =new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Documents and Settings\\icyleaf\\My Documents\\Visual Studio 2005\\WebSites\\WebShop\\App_Data\\WebShopDateSource.mdb ");
OleDbCommand cmd = new OleDbCommand( "SELECT Picture FROM dbo_Categories WHERE CategoryID= "+id,conn);
try
{
conn.Open();
Byte[] bt = (Byte[])cmd.ExecuteScalar();

Response.ClearContent();
Response.ContentType = "image/Gif ";

Response.BinaryWrite(bt);

}
catch (Exception e)
{
Response.Write( " <h1> wrong!!!!!! </h1> "+e);
}
finally {
Response.End();
conn.Close();

}


}
这段代码可以说基本是在网上抄的咯``但我读出来之后还是个叉叉```
aspx文件里的代码是这样的
<%@ Page Language= "C# " AutoEventWireup= "true " CodeFile= "WriteImages.aspx.cs " Inherits= "WriteImages " %>
只有这一句```

急求各位大侠帮忙下了```搞了好久了``不知道为什么```

[解决办法]
参考显示图片页的代码:
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString[ "id "];
if (id != null && id.CompareTo( " ") != 0)
{
string connStr = ConfigurationManager.ConnectionStrings[ "ConnString "].ConnectionString;
string SqlStr = "SELECT * FROM test02 where id = " + id;
DataSet ds = new DataSet();

try
{
SqlConnection conn = new SqlConnection(connStr);
if (conn.State.ToString() == "Closed ") conn.Open();


SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
da.Fill(ds, "test01 ");
if (conn.State.ToString() == "Open ") conn.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Response.BinaryWrite((byte[])ds.Tables[0].Rows[0][ "pic "]);
Response.End();
}

}
catch (Exception ex)
{
Response.Write( "数据库错误,错误原因: " + ex.Message);
Response.End();
}
}
}


我看你应该是少了Response.End();
[解决办法]
aspx:
<asp:image id= "imgPhoto " runat= "server " ImageUrl= "ShowPhoto.aspx "> </asp:image>
ShowPhoto.aspx

cs:
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
SqlConnection conn=new SqlConnection()
conn.ConnectionString= "DataSource=localhost;Database=test;UserId=sa;Pwd=sa ";
string strSql= "select * from test where id=2 ";//这里假设获取id为2的图片
SqlCommand cmd=new SqlCommand(strSql,conn);
conn.Open();
SqlDataReader reader=cmd.ExecuteReader();
reader.Read();
Response.ContentType= "application/octet-stream ";
Response.BinaryWrite((Byte[])reader[ "FImage "]);
Response.End();
reader.Close();
}
}

参考一下

读书人网 >asp.net

热点推荐