I am trying to test storing images in a database, I got this code after searching on Google but it doesn't work:
On my aspx page I have a simple upload button and my database consists of a simple table with two attributes: Id and ImageContent.
Could anyone please check the above code?
Code:
protected void Button1_Click(object sender, EventArgs e) { string strImageName = @"E:\images.jpg"; Bitmap bNewImage = new Bitmap(strImageName); FileStream fs = new FileStream(strImageName, FileMode.Open, FileAccess.Read); //creating byte array to read image byte[] bImage = new byte[fs.Length]; //this will store images.jp in bImage byte array fs.Read(bImage, 0, Convert.ToInt32(fs.Length)); fs.Close(); fs = null; //open the database using odp.net and insert the data string connstr = @"Data Source=PC5-52;Initial Catalog=ImageUpload;User Id=lab;Password=123456;"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); string strQuery; strQuery = "INSERT INTO ImageStore (ID, ImageContent) values (" + "1," + " @pic)"; SqlParameter ImageParameter= new SqlParameter(); ImageParameter.SqlDbType = SqlDbType.Image; ImageParameter.ParameterName = "pic"; ImageParameter.Value = bImage; SqlCommand cmd = new SqlCommand(strQuery, conn); cmd.Parameters.Add(ImageParameter); cmd.ExecuteNonQuery(); Response.Write("Image has been added to database successfully"); cmd.Dispose(); conn.Close(); conn.Dispose(); }
Could anyone please check the above code?