Adsence750x90

Monday, July 5, 2010

Insert Image in to Database

Insert Image in to Database

datatype of image in database is Byte[], so we insert image byte in to Database

FileUploader controls is used to select file, FileUploader control have a property FileBytes it return byte array (byte[]) of image, this Byte[] is stored in dataBase

example


 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void ImageUploadToDataBase(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Your Connection string");
        try
        {
            con.Open();
            byte[] imageByte = FileUpload1.FileBytes;
            SqlCommand cmd = new SqlCommand("INSERT INTO table (image,imagename) VALUES (@0,@1))", con);
            object[] cmdParams = new object[2];
            cmdParams[0] = imageByte;
            cmdParams[1] = "Name of Image";
            for (int i = 0; i < cmdParams.Length; i++)
            {
                cmd.Parameters.AddWithValue(i.ToString(), cmdParams[i]);
            }
            cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
        }
        finally { con.Close(); }
       
    }
    
}

No comments: