How to store and retrieve Image in Database using C# ASP.Net jQuery
http://www.ashishblog.com/blog/how-to-store-and-retrieve-image-in-database-using-c-asp-net-jquery/
In this article, I’ll explain how to store and retrieve Image in Database using C# ASP.Net jQuery. There is many other way to do that but here is the easiest way to do it.
Database:
For this tutorial, I am using following database.
Database:
For this tutorial, I am using following database.
CREATE TABLE [dbo].[tblImage]( [ID] [int] IDENTITY(1,1) NOT NULL, [image] [image] NULL, CONSTRAINT [PK_tblImage] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO
Connection string:
Below is the connection string to connect to the database.
Below is the connection string to connect to the database.
<connectionStrings> <add name="TempConnectionString" connectionString="Data Source=ASHISH;Initial Catalog=Temp;Persist Security Info=True;User ID=sa;Password=Temp1234567" providerName="System.Data.SqlClient"/> </connectionStrings>
Page:
In this tutorial, there one aspx page and one handler.
1. UploadImage.aspx – To Store image into database
2. DisplayImage.aspx – To display image from handler
3. DisplayImage.ashx – To read image from database (Handler)
In this tutorial, there one aspx page and one handler.
1. UploadImage.aspx – To Store image into database
2. DisplayImage.aspx – To display image from handler
3. DisplayImage.ashx – To read image from database (Handler)
1. UploadImage.aspx
Below HTML Markup of the page, you will notice that I have placed FileUpload to upload image into database.
Below HTML Markup of the page, you will notice that I have placed FileUpload to upload image into database.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadImge.aspx.cs" Inherits="UploadImge" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Ashish Blog</title> </head> <body> <form id="form1" runat="server"> <strong>Upload Image into database</strong><br /> <br /> Select Image: <asp:FileUpload ID="FileUpload1" runat="server" /><br /> <br /> <asp:Button ID="butSubmit" runat="server" Text="Submit" onclick="butSubmit_Click" /><br /> <asp:Label ID="lblStatus" runat="server"></asp:Label> <br /> <br /> <a href="DisplayImage.aspx">Display Image</a></form> </body> </html>
Codebehind:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; public partial class UploadImge : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void butSubmit_Click(object sender, EventArgs e) { 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); } string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString; using( SqlConnection connection = new SqlConnection(cs)) { connection.Open(); string sql = "INSERT INTO tblImage(image) VALUES(@theImage) SELECT @@IDENTITY"; using (SqlCommand cmd = new SqlCommand(sql, connection)) { cmd.Parameters.AddWithValue("@theImage", imgByte); int id = Convert.ToInt32(cmd.ExecuteScalar()); lblStatus.Text = String.Format("Image is Uploaded successfully!! and Image ID is {0}", id); cmd.Dispose(); } connection.Close(); connection.Dispose(); } } catch(Exception ex) { lblStatus.Text = "There was an error" + ex.Message ; } } }
2. DisplayImage.aspx
Below HTML Markup of the page, you will notice that I have placed jQuery function to display Image from database. You may also notice that I created Img variable and call ReadImage.ashx handler by passing Image ID in scr attribute of Img then append this Img to div.display.
Below HTML Markup of the page, you will notice that I have placed jQuery function to display Image from database. You may also notice that I created Img variable and call ReadImage.ashx handler by passing Image ID in scr attribute of Img then append this Img to div.display.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DisplayImage.aspx.cs" Inherits="DisplayImage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#Button1").click(function (e) { $('.display').text(''); //clean div display var ID = $("#txtID").val(); if (ID.length > 0) { var newImage = $('<img />'); newImage.attr('src', 'ReadImage.ashx?id=' + ID); // call handler with id $('.display').append(newImage); } e.preventDefault(); }); }); </script> </head> <body> <form id="form1" runat="server"> Display Image<br /> <br /> Id <asp:TextBox ID="txtID" runat="server"></asp:TextBox> &nbsp;<asp:Button ID="Button1" runat="server" Text="Display" /> <br /> <br /> <div class="display"></div> <br /> <br /> </form> </body> </html>
3. DisplayImage.ashx (Handler)
<%@ WebHandler Language="C#" Class="ReadImage" %> using System; using System.Web; using System.Data.SqlClient; using System.IO; using System.Configuration; public class ReadImage : 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) { string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString; using( SqlConnection connection = new SqlConnection(cs)) { string sql = "SELECT image FROM tblImage WHERE id = @ID"; using (SqlCommand cmd = new SqlCommand(sql, connection)) { cmd.CommandType = System.Data.CommandType.Text; cmd.Parameters.AddWithValue("@ID", theID); connection.Open(); object theImg = cmd.ExecuteScalar(); try { return new MemoryStream((byte[])theImg); } catch { return null; } finally { cmd.Dispose(); connection.Close(); connection.Dispose(); } } } } public bool IsReusable { get { return false; } } }
Thanks
Download
How to store and retrieve Image in Database using C# ASP.Net jQuery
No comments:
Post a Comment