Thursday, 7 July 2011

file upload control by storing image on database as a binary image format

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUpload.aspx.cs" Inherits="FileUpload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.IO" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>

<body>
<form id="form1" runat="server">
Product Name:
<asp:TextBox id="txtProductName" runat="server" />
<br />
Product Image:
<asp:FileUpload id="FileUpload1" runat="server" />
<asp:Button id="btnSave" runat="server" Text="Save Product" onclick="btnSave_Click" />
<br /><br />
<asp:Label id="lblMessage" runat="server" />
</form>

</body>
</html>


CREATE TABLE [dbo].[Products](
[ID] [int] NULL,
[ProductName] [nvarchar](100) NULL,
[ProductImage] [varbinary](max) NULL
) ON [PRIMARY]












protected void btnSave_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string productName = txtProductName.Text;
byte[] productImage = FileUpload1.FileBytes;

string constr = "Data Source=TECH-SWAPNILM\\SQLEXPRESS; Initial Catalog=master; Integrated Security=true";
string query = "INSERT INTO Products(ProductName, ProductImage) VALUES(@ProductName, @ProductImage)";

SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(query, con);

com.Parameters.Add("@ProductName", SqlDbType.NVarChar).Value = productName;
com.Parameters.Add("@ProductImage", SqlDbType.VarBinary).Value = productImage;
con.Open();
int result = com.ExecuteNonQuery();
con.Close();

if (result > 0)
{
lblMessage.Text = "Product Saved Successfully";
}
}
else
{
lblMessage.Text = "Please Select Product Image File";
}
}

}

No comments:

Post a Comment