0
Reply

Requesting to review my code from retrieving image from sql database

India Programmer

India Programmer

Nov 10 2009 7:54 AM
3.8k
Hi all, I have written code to insert and retrieve image from sqldatabase. But whenever i am inserting any image its checking catch section like. catch { lblStatus.Text = "There was an error"; } Pls somebody help me whats wrong with my code. Here is my all the code: Default.aspx:
Title:   
Image:




Default.aspx.cs: protected void butSubmit_Click(object sender, EventArgs e) { SqlConnection connection = null; try { Byte[] imgByte = null; if (FileUpload1.HasFile && FileUpload1.PostedFile != null) { HttpPostedFile File = FileUpload1.PostedFile; imgByte = new Byte[File.ContentLength]; File.InputStream.Read(imgByte, 0, File.ContentLength); } connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString()); connection.Open(); string sql = "INSERT INTO Table1(title,image) VALUES(@theTitle, @theImage) SELECT @@IDENTITY"; SqlCommand cmd = new SqlCommand(sql, connection); cmd.Parameters.AddWithValue("@theTitle", txtTitle.Text); cmd.Parameters.AddWithValue("@theImage", imgByte); int id = Convert.ToInt32(cmd.ExecuteScalar()); lblStatus.Text = String.Format("ID is {0}", id); Image1.ImageUrl = "~/DisplayImg.ashx?id=" + id; } catch { lblStatus.Text = "There was an error"; } finally { connection.Close(); } } } DisplayImg:ashx: <%@ WebHandler Language="C#" Class="DisplayImg" %> using System; using System.Web; using System.Configuration; using System.IO; using System.Data; using System.Data.SqlClient; public class DisplayImg : IHttpHandler { public void ProcessRequest (HttpContext context) { Int32 theID; if (context.Request.QueryString["id"] != null) theID = Convert.ToInt32(context.Request.QueryString["id"]); else throw new ArgumentException("No parameter specified"); context.Response.ContentType = "image/jpeg"; Stream strm = DisplayImage(theID); byte[] buffer = new byte[2048]; int byteSeq = strm.Read(buffer, 0, 2048); while (byteSeq > 0) { context.Response.OutputStream.Write(buffer, 0, byteSeq); byteSeq = strm.Read(buffer, 0, 2048); } } public Stream DisplayImage(int theID) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString.ToString()); string sql = "SELECT image FROM Table1 WHERE id = @ID"; SqlCommand cmd = new SqlCommand(sql,connection); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ID", theID); connection.Open(); object theImg = cmd.ExecuteScalar(); try { return new MemoryStream((byte[])theImg); } catch { return null; } finally { connection.Close(); } } public bool IsReusable { get { return false; } } } Thanks, India programmer