Tuesday, 5 March 2013

How to store image into database?


How to store image into database?

1.takes a FileUpload control(i.e. FileUpload1) and  a button(i.e. Button1 )
2.create a folder into  your web site(i.e. image)
3.write the following code to click event of Button1
code:-
protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con;
        SqlCommand cmd;
        DataSet ds;
        SqlDataAdapter adpt;
        Int32 result;
        string path = "~\\image" + "\\" + FileUpload1.FileName;
        
       con =new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\sunil\\Documents\\Visual Studio 2008\\WebSites\\EMS\\App_Data\\emsbd.mdf;Integrated Security=True;User Instance=True");
        //con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
        con.Open();
        cmd = new SqlCommand("INSERT INTO imgtable VALUES ('" + path + "')", con);
        cmd.CommandType = CommandType.Text;
        result = cmd.ExecuteNonQuery();
        
        if (result > 0)
        {
            FileUpload1.SaveAs(Server.MapPath(path));
            //Response.Write("user reg hae been completed successfully (into database)...");
        }
        else
        {
            Response.Write("error.............");
        }
        con.Close();
    }

4.here in above code change connection string to your connection string.
5.create a table name imgtable into database(here we take only one column),column data type like nvarchar/nchar.

No comments:

Post a Comment