ここで少し問題があります。
私のページでは、データベースからすべての「プロジェクト」を読み取るために asp:repeater を使用しています。現在、各プロジェクトには 2 つの画像 (バイナリ データ) も含まれており、それらをハンドラーで画像に変換し、ハンドラー ファイルを画像参照として使用したいと考えています。
私はこのコードをウェブで見つけました。それがどのように機能するかも知っていますが、ハンドラーで使用する方法がわかりません:
public Byte[] Ret_image(Int32 id)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Project where Id=@id";
cmd.Connection = con;
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Byte[] ar = (Byte[])(dr[1]);
dr.Close();
cmd.Dispose();
return ar;
}
これはおそらくうまくいくと思います。各プロジェクトの ID を指定するだけでよいと思いますが、これを実装する方法がよくわからず、上記のコードが正しいかどうかさえわかりません。
誰でも私を助けることができますか?
前もって感謝します!
[編集]
ハンドラーに必要な ID を与えるにはどうすればよいですか?
<asp:Image ID="img" ImageUrl="Image.ashx" runat="server" Height="80" Width="75%" />
または、ハンドラー内から正しい ID を取得するにはどうすればよいですか?
[編集2]
私は何を間違っていますか?画像は表示されませんが、見つからないとは言いません。
<asp:img class="icon-img icon-img_shadow" src="Image.ashx?ID=<%# DataBinder.Eval(Container, "DataItem.id") %>" alt="Icon" width="152" height="140" />
ハンドラーのコード:
public void ProcessRequest (HttpContext context) {
int id = Convert.ToInt32(context.Request.QueryString["ID"]);
context.Response.ContentType = "image/png";
MemoryStream strm = new MemoryStream(Ret_image(id));
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
public Byte[] Ret_image(Int32 id)
{
SqlConnection sqlCn = new SqlConnection("Data Source=server;Initial Catalog=db;User ID=user;Password=pw");
string qry = "SELECT * FROM Project WHERE imageid=@id";
SqlCommand cmd = new SqlCommand(qry, sqlCn);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
sqlCn.Open();
dr.Read();
Byte[] ar = (Byte[])(dr[1]);
dr.Close();
cmd.Dispose();
sqlCn.Close();
return ar;
}