Suppose you have database with following fields;
Now suppose you have already insert some data in table something like this;
You can see how make ASP.Net page to insert image in Database
Adding HTTPHandler:
To add HTTPHandler right click on the project explorer --> AddNewItem --> Generic Handler from the templete eg given pic below and Name it as ImageHanlder.ashx ;
Create a procedure like Proc_GetImageFromDataBase in database.
create procedure Proc_GetImageFromDataBase
@ImageID int
AS
begin
select * from InsertImageDemoTable where ImageID =@ImageID
end
Now Coding for ImageHandler.ashx
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public class ImageHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
string strId = context.Request.QueryString["Id"];
if (!string.IsNullOrEmpty(strId))
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Cms"].ConnectionString);
SqlDataReader sqlDr = null;
try
{
conn.Open(); //open database connection
SqlCommand sqlCmd = new SqlCommand("Proc_GetImageFromDataBase", conn);
sqlCmd.CommandType = CommandType.StoredProcedure;
//Add the parameter to SQLCommand object
sqlCmd.Parameters.AddWithValue("@Imageid", strId);
sqlDr = sqlCmd.ExecuteReader();
sqlDr.Read();
context.Response.BinaryWrite((Byte[])sqlDr[2]);
context.Response.End();
}
catch (Exception ex)
{
//Handle error If occured
}
finally
{
if (sqlDr != null && !sqlDr.IsClosed)
{
//close SqlDataReader
sqlDr.Close();
}
//close database connection
conn.Close();
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
Now add a new form in your project like this;
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default16.aspx.cs" Inherits="Default16" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtImageName" runat="server" Width="110px"> </asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" runat="server"
OnClick="btnUpload_Click" Text="Upload" style="height: 26px"/>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="Header Text" />
<asp:TemplateField HeaderText="Image Form DataBase">
<ItemTemplate>
<img alt="Image" height="70px" src='<%# "ImageHandler.ashx?Id="+ Eval("ImageId") %>' width="70px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Coding for .cs Class
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;
using System.Data;
public partial class Default16 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Load_GridData();
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strImageName = txtImageName.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Cms"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO InsertImageDemoTable(ImageName,Image)" +
" VALUES (@ImageName,@Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter
("@Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
}
}
private void Load_GridData()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Cms"].ConnectionString;
conn.Open(); // open the connection
SqlDataAdapter Sqa = new SqlDataAdapter("select * from InsertImageDemoTable", conn);
DataSet ds = new DataSet();
Sqa.Fill(ds); // fill the dataset
GridView1.DataSource = ds; // give data to GridView
GridView1.DataBind();
conn.Close();
}
}
Gridview something look like this:
No comments:
Post a Comment