How to Upload Images to Databases or How to Store Images to Database

I want to write this article using Layer Architecture.

database1.gif

This is the screen design. I want to store a product type image into the database.

I want to enter Product Type Name and that Image.

database2.gif

Presentation Layer

You have to write code for the Button Click event:

protected void Button2_Click(object sender, EventArgs e)
    {
        lblMessage.Visible = true;
        p.ProductType = txtName.Text;
        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);
            p.Image = imageSize;
        }

        p.InsertProducts();
        lblMessage.Text = "File Uploaded";

    }

Business Access Layer

public void InsertProducts()
    {
        SqlParameter[] p=new SqlParameter[2];
        p[0]=new SqlParameter("@ProductType",producttype);
        p[0].DbType=DbType.String;
        p[1]=new SqlParameter("Image",image);

        SqlHelper.ExecuteNonQuery(clsConnection.Connection,
CommandType.StoredProcedure, "sp_InsertProducts", p);
    }

// Here "sp_InsertProducts" is the stored procedure Name.

Data Access Layer

public class clsConnection
{
      public clsConnection()
      {
            //
            // TODO: Add constructor logic here
            //
      }
    public static string Connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}


Under Web.Config

<connectionStrings>
<
add name="ConnectionString" connectionString="user Id=sa;Password=123;DataBase=RentalShopping;Data Source=server2" providerName="System.Data.SqlClient"/>

</connectionStrings>

//Here write your database name,userid,password,datasource.

Under DataBase:

Create one database i.e RentalShopping.Under Database create one table.I have created one table i.e Products.

CREATE TABLE [dbo].[Products]
(
      [ProductId] [int] IDENTITY(101,1) NOT NULL,
      [ProductType] [varchar](50) NULL,
      [Image] [image] NULL
}

This is the Stored Procedure
USE [RentalShopping]
GO
-SET
ANSI_NULLS ON
GO
SET
QUOTED_IDENTIFIER ON
GO
ALTER
PROCEDURE [dbo].[sp_InsertProducts](@ProductType varchar(50),@Image image)
as
begin
  insert into Products(ProductType,Image)values(@ProductType,@Image)
  end


Similar Articles