Default.aspx
Código:
ImgHandler.ashxprotected void Page_Load(object sender, EventArgs e) { SqlConnection connection = null; try { // Insert the employee name and image into db string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; connection = new SqlConnection(conn); connection.Open(); string sql = "select TOP 1 ItemId from RubrikkImg.dbo.Attachment"; SqlCommand cmd = new SqlCommand(sql, connection); int ItemId = Convert.ToInt32(cmd.ExecuteScalar()); lblResult.Text = String.Format("ItemId is {0}", ItemId); // Display the image from the database Image1.ImageUrl = "~/ImgHandler.ashx?ItemId=" + ItemId; } catch { lblResult.Text = "There was an error"; } finally { connection.Close(); } }
Código:
<%@ WebHandler Language="C#" Class="ImgHandler" %> using System; using System.Configuration; using System.Web; using System.IO; using System.Data; using System.Data.SqlClient; using RubrikkImg; using System.Collections.Generic; public class ImgHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string empno; if (context.Request.QueryString["ItemId"] != null) empno = context.Request.QueryString["ItemId"].ToString(); else throw new ArgumentException("No parameter specified"); context.Response.ContentType = "jpeg/bmp"; Stream strm = ShowEmpImage(empno); 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); } context.Response.BinaryWrite(buffer); } public Stream ShowEmpImage(string empno) { string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(conn); string sql = "SELECT Contents FROM RubrikkImg.dbo.Attachment WHERE ItemId = @ID"; SqlCommand cmd = new SqlCommand(sql,connection); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ID", empno); connection.Open(); object img = cmd.ExecuteScalar(); try { return new MemoryStream((byte[]) img); } catch { return null; } /*finally { connection.Close(); }*/ } public bool IsReusable { get { return false; } } }