Thursday, February 10, 2011

Storing image into database and retrieve from database and display in web form image control

code for Aspx.cs Page

protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //typecasete imageupload control in a varaiable
                FileUpload img = (FileUpload)imgUpload;
                Byte[] imgByte = null;
                if (img.HasFile && img.PostedFile != null)
                {
                    //To create a PostedFile
                    HttpPostedFile File = imgUpload.PostedFile;
                    //Create byte Array with file len
                    imgByte = new Byte[File.ContentLength];
                    //force the control to load data in array
                    File.InputStream.Read(imgByte, 0, File.ContentLength);
                }
                // Insert the employee name and image into db
                connection.Open();
                string sql = "INSERT INTO image_test(image_name,image_source) VALUES(@image_name, @image_source)";
                SqlCommand cmd = new SqlCommand(sql, connection);
                cmd.Parameters.AddWithValue("@image_name", imgUpload.PostedFile.FileName.ToString() );
                cmd.Parameters.AddWithValue("@image_source", imgByte);
                cmd.ExecuteNonQuery();
                connection.Close();                       
            }
            catch
            { lblResult.Text = "There was an error"; }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            // For reading image from database and display in a image control in web form.
            Image1.ImageUrl = "~/image.ashx?image_name=" + txt_imageshow.Text.Trim();
        }


Next step add ashx extension file with following instruction:

click project > Add New Item > Generic Handler > image.ashx

then write the code in the form. 

public void ProcessRequest(HttpContext context)
        {
            string image_name = null;
            if (context.Request.QueryString["image_name"] != null)
               image_name  = Convert.ToString(context.Request.QueryString["image_name"]);
            else
                throw new ArgumentException("No parameter specified");

            context.Response.ContentType = "image/jpeg";
            Stream strm = ShowEmpImage(image_name);
            byte[] buffer = new byte[strm.Length];
            int byteSeq = strm.Read(buffer, 0, Convert.ToInt32(strm.Length));

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }       
           // context.Response.ContentType = "text/plain";
           // context.Response.Write("Hello World");
        }
        public Stream ShowEmpImage(string image_name)
        {
           
            string sql = "SELECT image_source FROM image_test WHERE image_name = @name";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@name", image_name);
            connection.Open();
            object img = cmd.ExecuteScalar();
            try
            {
                return new MemoryStream((byte[])img);
            }
            catch
            {
                return null;
            }
            finally
            {
                connection.Close();
            }
        }