可以使用的HttpHandler從數據庫retrive圖像。
<ItemTemplate>
<asp:Image ID="imgPhoto" runat="server"/>
</ItemTemplate>
如果您有一個圖像作爲DataGrid中的ItemTemplate。
在DataGrid的ItemDataBound事件中,調用「HttpHandler」來顯示圖像。在下面的代碼中,我找到了圖像控件並將imageUrl作爲HttpHandler文件路徑。我還將該ID作爲查詢字符串傳遞給HttpHandlerFile。
System.Web.UI.WebControls.Image photoImage = (System.Web.UI.WebControls.Image)e.Item.FindControl("imgPhoto");
photoImage.ImageUrl = "ImageHandler.ashx?PhotoID=" + id.ToString();
而在HttpHandler的文件中使用的LINQ以檢索圖像並顯示它。
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "image/jpeg";
int photoId = -1;
//Check the query string.
if (context.Request.QueryString["PhotoId"] != null && context.Request.QueryString["PhotoId"] != "")
{
photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
}
if (photoId != -1)
{
MovieDataContext db = new MovieDataContext();
//Get the movie record based on the ID
MovieTable movie = db.MovieTables.First(m => m.ID == photoId);
System.Data.Linq.Binary fileBinary = movie.Photo;
byte[] fileByte = fileBinary.ToArray();
//displays the Image.
context.Response.BinaryWrite(fileByte);
}
}
由於這個HttpHandler的文件映射到DataGrid中IMAGEURL,你可以看到在DataGrid中顯示的圖像。