How to store Image in database using “Image datatype
Introduction- In this article, I will explain how we can store image in the database. This is very interesting article. The need to store image in database occur, when there is a issue of security. I mean we can store the image of the signature of the human, becoz of the banking security. To store the image in the database, here I am using byte[] array. First I will convert the image into byte array[] and then it will store in the database.
Implementation- Create a website, create a page named storeimage.aspx. Place a textbox named txt_name and a fileuploader named upload_image. Here textbox will use to enter the image name and fileuploader is used to upload the image. Also place a gridview at this page to show the image.Then go to the website menu and place a Handler.ashx file.
Database
Create a table named addimage. Here iam explainning the columns that we need for a table to insert the image in the data base.
Column datatype
Id int (set its auto increment property)
Imagename varchar(50)
Image image
HTMl code for storeimage.aspx page
<%--<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:FileUpload ID="img_uploader" runat="server" /><br />
<br />
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" /><br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label><br />
<br />
<br />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName"
SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:cnn %>"
SelectCommand="SELECT [ID], [ImageName], [Image]
FROM [Images]"></asp:SqlDataSource>
</div> --%>
Code for storeimage.aspx.cs page
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
// i need the using system.IO named namespace to store the image in the database.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
// the str_imagename variable is use yo store the imagename from textbox.
string str_ImageName = txtName.Text.ToString();
if (img_uploader.PostedFile != null && img_uploader.PostedFile.FileName != "")
{
// here i am using a byte array type variable named imagesize to store the length of the image.
byte[] image_Size = new byte[img_uploader.PostedFile.ContentLength];
// here i am using httppostedfile type object to store the image that will store in the postedfile
HttpPostedFile uploadedImage = img_uploader.PostedFile;
// here i am using inputstream.read method to read the image size in the byte array
uploadedImage.InputStream.Read(image_Size, 0, (int)img_uploader.PostedFile.ContentLength);
// here i am creating the sqlconnection to store the image in database.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
// this is a sql query which will store the imagename and image that's converted in byte array, in the table
cmd.CommandText = "INSERT INTO addimage (ImageName,Image) VALUES (@ImageName,@Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
// here i am passing a parameter to store the imagename in the database.
SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
ImageName.Value = str_ImageName.ToString();
cmd.Parameters.Add(ImageName);
// her i am passing the parameter to store the image in the database
SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image_Size.Length);
UploadedImage.Value = image_Size;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
// after uploading the image the label will display.
lblMessage.Text = "File Uploaded";
// i am using imagehandler to bind the gridview with the image after fetching from the database.
GridView1.DataBind();
}
}
}
Handler.ashx code
// here I am explain how we can fetch data from database and show it into the database.
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
// sql query to select image and image name from the table.
cmd.CommandText = "Select addimage,Image from Images where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
// here i am passing parameter.
SqlParameter ImageID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
// this code read the binary of the image
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
// i need the using system.IO named namespace to store the image in the database.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
// the str_imagename variable is use yo store the imagename from textbox.
string str_ImageName = txtName.Text.ToString();
if (img_uploader.PostedFile != null && img_uploader.PostedFile.FileName != "")
{
// here i am using a byte array type variable named imagesize to store the length of the image.
byte[] image_Size = new byte[img_uploader.PostedFile.ContentLength];
// here i am using httppostedfile type object to store the image that will store in the postedfile
HttpPostedFile uploadedImage = img_uploader.PostedFile;
// here i am using inputstream.read method to read the image size in the byte array
uploadedImage.InputStream.Read(image_Size, 0, (int)img_uploader.PostedFile.ContentLength);
// here i am creating the sqlconnection to store the image in database.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
// this is a sql query which will store the imagename and image that's converted in byte array, in the table
cmd.CommandText = "INSERT INTO addimage (ImageName,Image) VALUES (@ImageName,@Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
// here i am passing a parameter to store the imagename in the database.
SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
ImageName.Value = str_ImageName.ToString();
cmd.Parameters.Add(ImageName);
// her i am passing the parameter to store the image in the database
SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image_Size.Length);
UploadedImage.Value = image_Size;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
// after uploading the image the label will display.
lblMessage.Text = "File Uploaded";
// i am using imagehandler to bind the gridview with the image after fetching from the database.
GridView1.DataBind();
}
}
}
Handler.ashx code
// here I am explain how we can fetch data from database and show it into the database.
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
// sql query to select image and image name from the table.
cmd.CommandText = "Select addimage,Image from Images where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
// here i am passing parameter.
SqlParameter ImageID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
// this code read the binary of the image
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
No comments:
Post a Comment